Array Function in PHP
PHP provides various array functions to access and manipulate the elements of array. The important PHP array functions are given below.
Extract()
- The extract() function to extract data from arrays and store it in variables.
- This function uses array keys as variable names and values as variable values. For each element it will create a variable in the current symbol table.
- This function returns the number of variables extracted on success.
Syntax:
extract(array)Example:
<?php
$color=array('red'=>1,'black'=>2,'green'=>3);
extract($color);
echo $red;
?>list()
list() function is also used to extract variables from an array.
list() is used with index array and associative array with numeric key.
For Example : Index array
<?php
$color=array("red","black","green");
list($a,$b,$c) = $color;
echo "value of a:$a ";
echo "value of b:$b ";
echo "value of c:$c ";
?>Compact()
- This function is opposite of extract() function.
- It returns an array with all the variables added to it.
- The compact() functions create associative array whose key value are the variable name and whose values are the variable values.
Example:
<?php
$var1="PHP";
$var2="JAVA";
$var3=compact("var1","var2");
print_r($var3);
?>implode()
- The implode() function returns a string from the elements of an array.
- The implode() function accept its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments.
- The separator parameter of implode() is optional. However, it is recommended to always use two parameters for backwards compatibility.
Syntax:
implode(separator, array)- separator Optional. Specifies what to put between the array elements. Default is "" (an empty string)
- array Required. The array to join to a string
Example: Join array elements with a string.
<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
// Output: Hello World! Beautiful Day!
?>explode()
- The explode() function breaks a string into an array.
- The "separator" parameter cannot be an empty string.
Syntax:
explode(separator, string, limit)separator Required. Specifies where to break the string
- string Required. The string to split
- limit Optional. Specifies the number of array elements to return. Possible values:
- Greater than 0 - Returns an array with a maximum of limit element(s)
- Less than 0 - Returns an array except for the last limit elements()
- 0 - Returns an array with one element
Example: Break a string into an array.
<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ", $str));
// Output: Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )
?>array_flip()
The array_flip() function flips/exchanges all keys with their associated values in an array.
Syntax:
array_flip(array)- array Required. Specifies an array of key/value pairs to be flipped
- Return Value: Returns the flipped array on success. NULL on failure
Example: Flip all keys with their associated values in an array.
<?php
$a1 = array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$result = array_flip($a1);
print_r($result);
// Output: Array ( [red] => a [green] => b [blue] => c [yellow] => d )
?>unset()
- The unset() function is used to remove element from the array.
- The unset() function accepts a variable name as parameter and destroy or unset that variable.
Syntax:
unset($var,...)Example:
<?php
$xyz = array("CO","ME","CE");
print_r($xyz);
unset($xyz);
print_r($xyz);
?>array_values()
- The array_values() function returns an array containing all the values of an array.
- Return all the values of an array (not the keys)
- The returned array will have numeric keys, starting at 0 and increase by 1.
Syntax:
array_values(array)Example:
<?php
$a = array("Name"=>"Peter","Age"=>"41","Country"=>"USA");
print_r(array_values($a));
// Output : Array ( [0] => Peter [1] => 41 [2] => USA )
?>array_slice()
- The array_slice() function returns selected parts of an array.
- If the array have string keys, the returned array will always preserve the keys
Syntax:
array_slice(array, start, length, preserve)Example: start the slice from the third array element, and return the rest of the elements in the array.
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
// Output: Array ( [0] => blue [1] => yellow [2] => brown )
?>array_merge()
- The array_merge() function merges one or more arrays into one array.
- You can assign one array to the function, or as many as you like.
- If two or more array elements have the same key, the last one overrides the others.
- If you assign only one array to the array_merge() function, and the keys are integers, the function returns a new array with integer keys starting at 0 and increases by 1 for each value (See example below).
- The difference between this function and thearray_merge_recursive()function is when two or more array elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an array.
Syntax:
array_merge(array1, array2, array3, ...)Example 1:
<?php
$a1 = array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
// Output : Array ( [0] => red [1] => green [2] => blue [3] => yellow )
?>Example 2:
<?php
$a1 = array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge($a1,$a2));
// Output: Array ( [a] => red [b] => yellow [c] => blue )
?> Sorting Arrays Functions
The elements in an array can be sorted in alphabetical or numerical order, descending or ascending.
sort() : sort arrays in ascending order
rsort() : sort arrays in descending order
asort() : sort associative arrays in ascending order, according to the value
ksort() : sort associative arrays in ascending order, according to the key
arsort() : sort associative arrays in descending order, according to the value
krsort() : sort associative arrays in descending order, according to the key
Example: Sorts the elements of the $cars array in ascending alphabetical order:
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>Example: Sorts the elements of the $numbers array in ascending numerical order:
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
?>Array Iterator Functions
next() : move to next element in array
prev() : move to previous element in array
end() : move to last element in array
each() : return the key and value of current element in array
pos() : returns the value of the current element in an array.
current() : return current point element
key() : return the key of current element in array
reset() : move to first element in array
Example:
<?php
$people = array("Sumit", "Amita", "Shiv", "Mitali");
echo current($people) . "<br>";
echo next($people). "<br>";
echo prev($people). "<br>";
echo pos($people) . "<br>";
echo end($people). "<br>";
echo reset($people). "<br>";
echo "The key from the current position is: " . key($people)."<br>";
print_r (each($people));
?>Output:
Sumit
Amita
Sumit
Sumit
Mitali
Sumit
The key from the current position is: 0
Array (
[1] => Sumit
[value] => Sumit
[0] => 0
[key] => 0
)