PHP has a vast set of built-in functions that allow you to modify, search, and manage arrays efficiently. Understanding these functions is key to professional PHP development.
The count() function returns the number of elements in an array.
<?php
$fruits = ["Apple", "Banana", "Cherry"];
echo count($fruits); // Result: 3
?>
You can easily add or remove elements from the beginning or end of an array.
array_push(): Adds one or more elements to the end.array_pop(): Removes the last element.array_unshift(): Adds one or more elements to the beginning.array_shift(): Removes the first element.<?php
$stack = ["Orange"];
array_push($stack, "Apple", "Mango"); // ["Orange", "Apple", "Mango"]
array_pop($stack); // ["Orange", "Apple"]
?>
The array_merge() function merges one or more arrays into one.
<?php
$a1 = ["red", "green"];
$a2 = ["blue", "yellow"];
$result = array_merge($a1, $a2);
// Result: ["red", "green", "blue", "yellow"]
?>
The in_array() function checks if a specific value exists in an array.
<?php
$os = ["Windows", "Linux", "macOS"];
if (in_array("Linux", $os)) {
echo "Found Linux!";
}
?>
For associative arrays, you might need just the keys or just the values.
array_keys(): Returns all the keys.array_values(): Returns all the values.<?php
$age = ["Peter"=>"35", "Ben"=>"37", "Joe"=>"43"];
print_r(array_keys($age)); // ["Peter", "Ben", "Joe"]
?>
array_merge() will overwrite numeric keys if they collide, but they will append if the keys are integers. Always check the manual for specific behavior.
| Function | Description |
|---|---|
count() | Returns the number of elements. |
array_push() | Inserts elements at the end. |
array_merge() | Merges two or more arrays. |
in_array() | Checks if a value exists. |
array_slice() | Extracts a slice of the array. |
array_unique() | Removes duplicate values. |