PHP array functions
Array Functions
PHP provides a wide range of built-in functions to manipulate arrays. Here are some commonly used functions:
array_push()
: Adds one or more elements to the end of an array.<?php $fruits = array("Apple", "Banana"); array_push($fruits, "Cherry", "Date"); print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Banana [2] => Cherry [3] => Date ) ?>
array_pop()
: Removes the last element from an array.<?php $fruits = array("Apple", "Banana", "Cherry"); $last = array_pop($fruits); echo $last; // Outputs: Cherry print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Banana ) ?>
array_shift()
: Removes the first element from an array.<?php $fruits = array("Apple", "Banana", "Cherry"); $first = array_shift($fruits); echo $first; // Outputs: Apple print_r($fruits); // Outputs: Array ( [0] => Banana [1] => Cherry ) ?>
array_unshift()
: Adds one or more elements to the beginning of an array.<?php $fruits = array("Banana", "Cherry"); array_unshift($fruits, "Apple", "Date"); print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Date [2] => Banana [3] => Cherry ) ?>
array_merge()
: Merges one or more arrays into one.<?php $array1 = array("a", "b", "c"); $array2 = array("d", "e", "f"); $merged = array_merge($array1, $array2); print_r($merged); // Outputs: Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f ) ?>
array_slice()
: Extracts a portion of an array.<?php $array = array("a", "b", "c", "d", "e"); $slice = array_slice($array, 2, 2); print_r($slice); // Outputs: Array ( [0] => c [1] => d ) ?>
array_search()
: Searches for a value in an array and returns the corresponding key if found.<?php $array = array("a" => "Apple", "b" => "Banana"); $key = array_search("Banana", $array); echo $key; // Outputs: b ?>
array_keys()
: Returns all the keys of an array.<?php $array = array("a" => "Apple", "b" => "Banana"); $keys = array_keys($array); print_r($keys); // Outputs: Array ( [0] => a [1] => b ) ?>
array_values()
: Returns all the values of an array.<?php $array = array("a" => "Apple", "b" => "Banana"); $values = array_values($array); print_r($values); // Outputs: Array ( [0] => Apple [1] => Banana ) ?>
sort()
: Sorts an array in ascending order.<?php $array = array(3, 1, 4, 1, 5); sort($array); print_r($array); // Outputs: Array ( [0] => 1 [1] => 1 [2] => 3 [3] => 4 [4] => 5 ) ?>
rsort()
: Sorts an array in descending order.<?php $array = array(3, 1, 4, 1, 5); rsort($array); print_r($array); // Outputs: Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 1 [4] => 1 ) ?>
Array Iteration
foreach
LoopIterates over each element in an array.
Example:
<?php $fruits = array("Apple", "Banana", "Cherry"); foreach ($fruits as $fruit) { echo $fruit . "<br>"; } ?>
Associative Array Example:
<?php $person = array("first_name" => "John", "last_name" => "Doe", "age" => 30); foreach ($person as $key => $value) { echo "$key: $value<br>"; } ?>