Back to course

Useful Array Functions (Count, Push, Pop, Sort)

PHP: The Complete 0 to Hero Bootcamp

24. Useful Array Functions

PHP provides hundreds of built-in functions for array manipulation. Mastering these functions is crucial for writing efficient PHP code.

1. Counting and Checking

FunctionDescription
count($array)Returns the number of elements in an array.
is_array($var)Checks if a variable is an array (returns boolean).
array_key_exists($key, $array)Checks if a specified key exists in an array.

php

2. Adding and Removing Elements

FunctionDescription
array_push($array, $val1, ...)Adds elements to the end of an indexed array.
array_pop($array)Removes and returns the element from the end of the array.
array_unshift($array, $val1, ...)Adds elements to the beginning of an array.
array_shift($array)Removes and returns the element from the beginning of the array.

3. Sorting Arrays

FunctionDescription
sort($array)Sorts indexed array elements in ascending order (by value).
rsort($array)Sorts indexed array elements in descending order (by value).
asort($array)Sorts associative arrays by value (ascending).
ksort($array)Sorts associative arrays by key (ascending).

php

35, 'Joe' => 43, 'Amy' => 37]; ksort($ages); // Sort by name (key) print_r($ages); // Output: Array ( [Amy] => 37 [Joe] => 43 [Peter] => 35 ) ?>