PHP Array Functions

PHP provides many built-in array functions to make working with arrays easier. Whether you need to sort, search, modify, or filter an array, there’s a function for that!

🔹 Count the Number of Elements

To find out how many elements are in an array, use count().

<?php
$fruits = array("Apple", "Banana", "Cherry");
echo "Total Fruits: " . count($fruits);
?>

Try It Now

Output: Total Fruits: 3


🔹 Check if a Value Exists in an Array

Use in_array() to check if a value exists in an array.

<?php
$colors = array("Red", "Green", "Blue");

if (in_array("Green", $colors)) {
    echo "Green is in the array!";
} else {
    echo "Green is not found.";
}
?>

Try It Now

Output: Green is in the array!


🔹 Get the Keys of an Array

Use array_keys() to get all keys from an array.

<?php
$student = array("name" => "Alice", "age" => 24, "course" => "Math");
$keys = array_keys($student);
print_r($keys);
?>

Try It Now

Output: Array ( [0] => name [1] => age [2] => course )


🔹 Reverse an Array

Use array_reverse() to reverse an array.

<?php
$numbers = array(1, 2, 3, 4, 5);
$reversed = array_reverse($numbers);
print_r($reversed);
?>

Try It Now

Output: Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 )


🔹 Merge Two Arrays

Use array_merge() to combine multiple arrays.

<?php
$first = array("A", "B", "C");
$second = array("D", "E", "F");

$merged = array_merge($first, $second);
print_r($merged);
?>

Try It Now

Output: Array ( [0] => A [1] => B [2] => C [3] => D [4] => E [5] => F )


🔹 Remove the Last Element

Use array_pop() to remove and return the last element.

<?php
$animals = array("Dog", "Cat", "Elephant");
$last = array_pop($animals);

echo "Removed: $last <br>";
print_r($animals);
?>

Try It Now

Output:


Removed: Elephant
Array ( [0] => Dog [1] => Cat )


🔹 Sort an Array

Use sort() for ascending order and rsort() for descending order.

<?php
$numbers = array(5, 2, 8, 1, 9);
sort($numbers);
print_r($numbers);
?>

Try It Now

Output: Array ( [0] => 1 [1] => 2 [2] => 5 [3] => 8 [4] => 9 )


🎯 Key Takeaways

  • count() – Get the number of elements in an array.
  • in_array() – Check if a value exists in an array.
  • array_keys() – Get all keys from an array.
  • array_reverse() – Reverse the array.
  • array_merge() – Merge two or more arrays.
  • array_pop() – Remove the last element.
  • sort() – Sort an array in ascending order.

📝 Practice Time!

Try creating an array of your favorite superheroes 🦸‍♂️, and use array functions to sort, search, and modify it!