Arrays In PHP

; var_dump(array_merge($arr1, $arr2)); // values 27 and 38 clash, so their keys from $arr2 are used.

// so, output is paul (38), sean (27), and nick (27).

?>You can merge several arrays simultaneously by providing more parameters to the function.

For example:$sports_teams = array_merge($soccer, $baseball, $basketball, $hockey);array_pop()mixed array_pop (array $arr)The array_pop() function takes an array as its only parameter and returns the value from the end of the array while also removing it from the array.

For example:<?php $names = array("timmy", "bobby", "sam", "tammy", "joe"); $FirstName = array_pop($names); // first is timmy, last is joe again?>array_push()int array_push (array $arr, mixed var [, mixed .

])The array_push() function takes an array and a new value as its only parameter, and pushes that value onto the end of the array, after all the other elements.

This is the opposite of the array_pop() function:<?php $firstname = "johnny"; $names = array("timmy", "bobby", "sam", "tammy", "joe"); array_push($names, $firstName); // first is timmy, last is now johnny?>array_rand()mixed array_rand(array arr [, int amount])The array_rand() function picks out one or more random values from an array.

It takes an array to read from, then returns either one random key or an array of random keys from inside there.

The advantage to array_rand() is that it leaves the original array intact, so you can just use that randomly chosen key to grab the related value from the array.

There is an optional second parameter to array_rand() that allows you to specify the number of elements you would like returned.

These are each chosen randomly from the array and are not necessarily returned in any particular order.

The function also has these attributes.

It returns the keys in your array.

If these aren’t specified, the default integer indexes are used.

To get the value out of the array, look up the value at the key.

If you ask for one random element or do not specify parameter two, you will get a single randomly chosen variable back.

If you ask for more than one random element, you will receive an array of variables back.

If you ask for more random elements than there are in the array, you will get an error.

If you request more than one random element, it will not return duplicate elements.

If you want to read most or all of the elements from your array in a random order, use a mass randomizer like shuffle(), as it is faster.

With that in mind, here’s an example of array_rand() in action:<?php $natural_born_killers = array("lions", "tigers", "bears", "kittens"); $two_killers = array_rand();?>array_shift()mixed array_shift (array $arr)The array_shift() function takes an array as its only parameter and returns the value from the front of the array while also removing it from the array.

For example:<?php $names = array("johnny", "timmy", "bobby", "sam", "tammy", "joe"); $FirstName = array_shift($names); // "johnny" var_dump($names); // timmy, bobby, sam, tammy, danny, and joe ?>array_unique()array array_unique (array arr)The array_unique() filter an array so that a value can only appear once.

It takes an array as its only parameter and returns the same array with duplicate values removed.

For example:<?phps $toppings2 = array("peppers", "ham", "cheese", "peppers" ); $toppings2 = array_unique($toppings2); // now contains "peppers", "ham", and "cheese"?>array_values()array array_values (array arr)The array_values() takes an array as its only parameter and returns an array of all the values in that array.

This might seem pointless, but its usefulness lies in how numerical array is indexed.

If you use the array operator [] to assign variables to an array, PHP will use 0,1,2,3 etc.

as the keys.

If you then sort the array using a function such as asort(), which keeps the keys intact, the array’s keys will be out of order because of asort() sort by values, not by key.

Using the array_values() function makes PHP create a new array where the indexes are recreated and the values are copied from the old array, essentially making it renumber the array element.

For example:<?php $words = ("hello", "world", "foo", "bar", "baz");var_dump($words);// prints the array out in its original ordering, so // array (5) {[0] => string (5) "hello" [1] => string(5) // "world" [2] => string (3) "foo" [3] => string(3) = "bar" // [4] => string(3) "bar"}asort($words);var_dump(array_values($words));// array_values() creates a new array, re-ordering the keys, so: // array(5) {[0]=> string (3) "bar" [1]=> string (3) "baz" // [2] => string(3) "foo" [3]=> string (5) "hello" // [4]=> string(5) "world"}?>You will find array_values() useful to reorder an array’s indexes either because they are jumbled up or because they have holes in them, but you can also use it to convert an associative array with strings as the indexes to a plain numerical array.

arsort()bool arsort (array $arr [, int options])The arsort() function takes an array as its only parameter, and reverse sorts it by its values while preserving the keys.

This is the opposite of the asort().

For example:<?php $capitalcities ["england"] = "london"; $capitalcities ["wales"] = "cardiff"; $capitalcities ["scotland"] = "edingburgh"; arsort($capitalcities); // reverse-sorted by value, so london, edingburgh, cardiff ?>Note that arsort() works by reference, directly changing the value you pass in.

The return value is either true or false, depending on whether the sorting was successful.

By default, the sort functions sort so that 2 comes before 10.

You can change this using the second parameter — see the ksort() reference for how to do this.

MULTIDIMENSIONAL ARRAYCurrently, our arrays just hold standard, non-array variable, which makes them one-dimensional.

In contrast, a two-dimensional array is where each element holds another array as its value, and each element is the child arrays holds a non-array variable.

This allows us to store arrays within the array and therefore lets us store much more information.

Consider this script:<?php $capitalcities["england"] = array('capital' => "london", "population" => 4000000, "nationalsport" => "cricket" ); $capitalcities["wales"] = array('capital' => "cardiff", "population" => 5000000, "nationalsport"=> "rugby" ); $capitalcities["scotland"] = array('capital' => "edinburgh", "population" => 800000, "nationalsport" => "football" );var_dump($capitalcities);?>That creates the $capitalcities array elements as before but uses an array for each value.

Each child array has three elements: capital, population, and nationalsport.

At the end, there is a var_dump() call on the parent array, which gives this output:array(3) { ["england"] => array(3) {["capital"] => string (6) = "london" ["population"] => int (4000000) ["nationalsports"]=> string(7) "cricket" }["wales"] => array(3) {["capital"] => string(7) "cardiff" ["population"]=> int(5000000) ["nationalsports"] => string(5) "rugby" }["scotland"] => array(3) {["capital"] => string(9) "edinburgh" ["population"] => int(800000) ["nationalsport"] => string(8) "football" }}Not only does var_dump() recurse into child arrays to output their contents too, but it indents all the output according to the array level.

THE ARRAY CURSOREach array has a “cursor,” which you can think of as an arrow pointing to the next array element in line to be operated on.

It is the array cursor that allows code like while (list($var, $val) = each($array)) to work — each () moves forward the array cursor of its parameter each time it is called, until it eventually finds itself at the end of the array, and so return false, ending the loop.

The each() function does not move the array cursor back to the first element when you first call it, it just picks up from where the cursor was.

It is in situations like this where you need to set the position of the array cursor forcibly, and the functions reset(), end(), next(), and prev() do just that.

They all take just one parameter — the array to work with, and return a value from the array.

You use the reset() function to rewind its parameter’s cursor to the first element, then return the value of that element, whereas end() will set the array cursor to the last element and return that value.

The next() and prev() functions both move the cursor pointer forward or backward one element respectively, returning the value of the element now pointed to.

If any of the four functions cannot return a value, they will return false.

As such, you can use them all in loops if you want: For example,<?php $array = array("foo", "bar", "baz", "wom", "bat" ); print end($array);while ($val = ($array)) { print $val; }?>Note that we print the output of end() because it sets the array cursor to point at “bat”, and prev() will shift the array cursor back one to “wom”, meaning that “bat” would otherwise not be printed out.

HOLES IN ARRAYUsing prev() and next() is more difficult when using arrays that have holes.

For example:<?php $array["a"] = "foo"; $array["b"] = ""; $array["c"] = "baz"; $array["d"] = "wom"; print end($array);while($val = prev($array)) { print $val; }?>You may think that will iterate over an array in reverse, printing out values as it goes; however, the value at key b is empty, which will cause both prev() and next() to think that the end of the array has been reached.

So, when they hit b, they will return false, prematurely ending with a while loop.

In this situation, it would have been better to reverse the array, then use each() to iterate over it.

This will cope fine with empty variables and unknown keys.

USING ARRAYS IN STRINGSIf you want to print array data inside a string, you need to use braces, { and }, around the variables to tell PHP that you are passing it an array to read from.

This next code shows how:$myarray['foo'] = 'bar';print 'this is from an array: {$myarray['foo']}.'.

. More details

Leave a Reply