Hello World, In this article, we will discuss 9 Useful Php Array Functions. I will discuss some functions in some detail and with an example. Following are some steps are given below to run the array function.
print_r()
This function is used to print an array with its key and value. this function read like key automatically 0=>ram 1=>sham etc. but we can define our custom key like ram=>age ram=>DOB etc. In this, ram is key and age and DOB is its value.
<?php $a= ['ram','sham','geeta']; print_r ($a); ?> //Output: //Array ( [0] => ram [1] => sham [2] => geeta )
explode()
This function is used to convert a string into an array. we can use value and variable names to explode the string.
<?php $a= "it is string"; print_r (explode(" ",$a)); ?> //Output: Array ( [0] => it [1] => is [2] => string )
implode()
This function is used to convert the array into a string. we can use value and variable name to implode the array.
<?php $a= ['ram','is','a','good','boy.']; print_r (implode(" ",$a)); ?> //Output: ram is a good boy
sort()
This function is sort array in ascending order by its value.
<?php $name=['ram','sham','geeta','sita']; echo '<pre>'; sort($name); print_r ($name); '</pre>'; ?> Output: Array ( [0] => geeta [1] => ram [2] => sham [3] => sita )
asort()
This function is to sort the array’s value in ascending order. In this function, the key is set according to the array’s value.
<?php $name=['ram','sham','geeta','sita']; echo '<pre>'; asort($name); print_r ($name); '</pre>'; ?> Output: Array ( [2] => geeta [0] => ram [1] => sham [3] => sita )
ksort()
This function is a short array’s key in ascending order. In this function, the value is set according to the array’s key.
<?php $name=['ram','sham','geeta','sita']; echo '<pre>'; asort($name); print_r ($name); '</pre>'; ?> Output: Array ( [0] => ram [1] => sham [2] => geeta [3] => sita )
rsort()
This function is sort array in descending order.
<?php $name=['ram','sham','geeta','sita']; echo '<pre>'; sort($name); print_r ($name); '</pre>'; ?> Output: Array ( [0] => sita [1] => sham [2] => ram [3] => geeta )
arsort()
This function is a short array’s value in descending order. In this function, the key is set according to the array’s value.
<?php $name=['ram','sham','geeta','sita']; echo '<pre>'; asort($name); print_r ($name); '</pre>'; ?> Output: Array ( [3] => sita [1] => sham [0] => ram [2] => geeta )
krsort()
This function is a short array’s key in descending order. In this function, the value is set according to the array’s key.
<?php $name=['ram','sham','geeta','sita']; echo '<pre>'; asort($name); print_r ($name); '</pre>'; ?> Output: Array ( [3] => sita [2] => geeta [1] => sham [0] => ram )