PHP Array Functions
There are various array functions in PHP. They are used to access and manipulate the elements ofan array. Following are functions of array.
Array Function | Description |
array() | It is used to create an array. |
array_change_key_case() | It is used to convert lowercase or uppercase of all keys in an array. |
array_chunk() | It is used to split an array into chunks of arrays. |
array_pop() | It is used to delete the last element of an array. |
array_merge() | It is used to merge one or more arrays into one array. |
array_rand() | It is used to returns one or more random keys from an array. |
array_reverse() | It returns an array in the reverse order. |
array_search() | It searches an array for a given value and returns the key. |
count() | It returns the number of elements in an array. |
extract() | It imports variables into the current symbol table from an array. |
sort() | PHP sort() function sorts all the elements in an array. |
- PHP array() function
<!DOCTYPE html> <html> <body> <?php $week=array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"); $arrlength=count($week); echo "=====To print Week days using an array======"."<br>"; for($x=0;$x<$arrlength;$x++) { echo $week[$x]; echo "<br>"; } ?> </body> </html>Output =====To print Week days using an array====== Sunday Monday Tuesday Wednesday Thursday Friday Saturday
- array_change_key_case() function
<!DOCTYPE html> <html> <body> <?php $salary=array("Sunday"=>"1","Monday"=>"2","Tuesday"=>"3"); print_r(array_change_key_case($salary,CASE_UPPER)); ?> </body> </html>Output
Array ( [SUNDAY] => 1 [MONDAY] => 2 [TUESDAY] => 3 )3). PHP array_chunk() function PHP array_chunk() function is used to split an array into chunks. We can divide array into many parts. Example
<!DOCTYPE html> <html> <body> <?php $salary=array("Sunday"=>"1","Monday"=>"2","Tuesday"=>"3"); print_r(array_chunk($salary,2)); ?> </body> </html>Output
Array ( [0] => Array ( [0] => 1 [1] => 2 ) [1] => Array ( [0] => 3 ) )PHP array_pop() Function PHP array_pop() function is used to delete last element of an array. Example
<?php $a=array("red","green","blue"); array_pop($a); print_r($a); ?>PHP count() Function PHP count() function is used to return the number of elements in an array. Example
<!DOCTYPE html> <html> <body> <?php $color=array("Red","Blue","Green","Magenta"); echo count($color); ?> </body> </html>Output 4 PHP sort() Function PHP short() function is used to sort the elements of an array in ascending order. Example
<!DOCTYPE html> <html> <body> <?php $color=array(27,21,83,11); sort($color); $clength=count($color); echo"Assending Order [27,21,83,11]"."<br>"; for($x=0;$x<$clength;$x++){ echo $color[$x]; echo "<br>"; } ?> </body> </html>Output Assending Order [27,21,83,11] 11 21 27 83