Yes! This is useful array methods of PHP – part 2 You have not read the first part you can click Useful PHP Array methods you should know.
Lets see the quick list of array methods of this article.
array_keys() used to get all the keys from an array. In part 1 we saw there are two types of array Associative and Indexed. So array_keys() with Indexed array returns indexes as keys and with associative array returns defined keys.
Let’s see an example to make it more clear.
//associative array $array = array(0 => 100, "color" => "red"); print_r(array_keys($array)); //output Array (  => 0  => color ); //keys as array //Indexed Array $array = array(100, "red"); print_r(array_keys($array)); //output Array (  => 0  => 1 ); //index positions as array
This is very similar to
array_keys() returns an array of keys
array_values() returns an array of values. As it returns array of values so it is obvious we can’t use it with indexed array as indexed array already an array of values.
//associative array $array = array(0 => 100, "color" => "red"); print_r(array_values($array)); //output Array (  => 100  => red ); //values as array
This one is kinda intresting so it is useful when you want to create an array one position to next position. Lets take a scenario where you have to create array of numbers from 1 to 5. How you will create it?, Like following
Okay,Thats right way to do this. What if I say create an array from 1-100 or 1-1000, will you do it like this? NO!
In this kind of scenario range can be used. Just pass the starting and ending number to
$rangeArray = range(1,25); print_r($rangeArray); //output Array (  => 1  => 2  => 3  => 4  => 5  => 6  => 7  => 8  => 9  => 10  => 11  => 12  => 13  => 14  => 15  => 16  => 17  => 18  => 19  => 20  => 21  => 22  => 23  => 24  => 25 )
Isn’t that cool!
Another array function widely used in laravel framework of PHP. So what it does, Basically it accepts multiple parameter like arrays. Lets see an example first then explanation could be useful.
$city = "San Francisco"; $state = "CA"; $event = "Annual Party"; $result = compact("event", "city", "state"); print_r($result); //output Array ( [event] => Annual Party [city] => San Francisco [state] => CA )
Have you noticed the parameter passed in
compact() function are actually variable names. Actually it create parameters as key and assign values of their variables associated with that.
Well, this one is not that hard to understand,
shuffle() the function accepts a parameter as an array and orders them randomly. It returns true and false not a randomized array.
$numbers = range(1, 25); shuffle($numbers); print_r($numbers); //output //everytime new order of 1-25
So that was all about useful array methods of PHP – part 2. If I have missed something or you are finding any difficulty in understanding, let me know in the comment box.