Array Functions in PHP
Introduction
Arrays are a fundamental part of PHP and are used to store collections of data. PHP provides a wide array of functions to work with arrays. These functions allow you to manipulate arrays in various ways, from sorting and merging to filtering and transforming. In this tutorial, we will explore some of the most commonly used array functions in PHP with examples.
Creating Arrays
Before diving into array functions, let's look at how to create arrays in PHP. There are two types of arrays: indexed arrays and associative arrays.
Indexed Array:
<?php $fruits = array("Apple", "Banana", "Cherry"); ?>
Associative Array:
<?php $ages = array("Peter" => 35, "John" => 42, "Jane" => 29); ?>
Common Array Functions
1. array_push()
The array_push()
function adds one or more elements to the end of an array.
<?php $stack = array("orange", "banana"); array_push($stack, "apple", "raspberry"); print_r($stack); ?>
Array ( [0] => orange [1] => banana [2] => apple [3] => raspberry )
2. array_pop()
The array_pop()
function removes the last element of an array.
<?php $stack = array("orange", "banana", "apple", "raspberry"); $fruit = array_pop($stack); print_r($stack); ?>
Array ( [0] => orange [1] => banana [2] => apple )
3. array_merge()
The array_merge()
function merges one or more arrays into one array.
<?php $array1 = array("color" => "red", 2, 4); $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4); $result = array_merge($array1, $array2); print_r($result); ?>
Array ( [color] => green [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4 )
4. array_diff()
The array_diff()
function compares two arrays and returns the values in the first array that are not present in the second array.
<?php $array1 = array("a" => "green", "red", "blue", "red"); $array2 = array("b" => "green", "yellow", "red"); $result = array_diff($array1, $array2); print_r($result); ?>
Array ( [1] => blue )
5. array_filter()
The array_filter()
function filters elements of an array using a callback function.
<?php function odd($var) { return($var & 1); } $array1 = array("a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5); $result = array_filter($array1, "odd"); print_r($result); ?>
Array ( [a] => 1 [c] => 3 [e] => 5 )
6. array_map()
The array_map()
function applies a callback to the elements of the given arrays.
<?php function cube($n) { return($n * $n * $n); } $a = array(1, 2, 3, 4, 5); $result = array_map("cube", $a); print_r($result); ?>
Array ( [0] => 1 [1] => 8 [2] => 27 [3] => 64 [4] => 125 )
Conclusion
Array functions in PHP are powerful tools that allow developers to manipulate and work with arrays in various ways. From adding and removing elements to merging, filtering, and transforming arrays, these functions provide a wide range of capabilities. Understanding and mastering these functions will greatly enhance your ability to work with arrays in PHP.