HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Array Functions

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.


1. Getting the Length

The count() function returns the number of elements in an array.

<?php
    $fruits = ["Apple", "Banana", "Cherry"];
    echo count($fruits); // Result: 3
?>

2. Adding and Removing Elements

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"]
?>

3. Merging Arrays

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"]
?>

4. Checking for Elements

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!";
    }
?>

5. Keys and Values

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"]
?>
Performance Tip: Built-in PHP functions are written in C and are much faster than writing your own logic using loops for basic tasks like searching or merging.
Caution: Functions like 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.

Commonly Used Array Functions

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.