PHP Array Function Tutorial

PHP array string functions are some of the most important functions you need to know in PHP if you want to become an efficient programmer. In this tutorial, we will look at the most commonly used array string functions, including (but not limited to) count, push, in_array, asort, and pop.

Quick Guide to Array Basics

PHP arrays are a simple way of storing numerous bits of information (such as strings) in a simple PHP variable, known as an “array variable”; you can retrieve this information by using its key index.

On the other hand, “strings” are a finite series of symbols from a set such as an alphabet. In PHP, you can designate a string with single or double quotes:

<?php
$string1= 'This is a string created by single quote';
$string2= "This is a string created by double quotes";
?>

Most of the information you gather in a PHP web form is in string data format. Storing strings in an array allows your code to use only a single PHP variable to store a lot of information. Supposing you would like to define an array variable that consist of the planets in the solar system, you would do so in the following manner:

<?php
//create an array variable $planets
$planets=array(); 
//store strings in the $planet array variable, which is essentially the name of the planets
$planets=array("Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune");
//dump all string information stored in the array variable to the browser
var_dump($planets);
?>

This will be the output:

array(8) {
[0]=>string(7) "Mercury"
[1]=>string(5) "Venus"
[2]=>string(5) "Earth"
[3]=>string(4) "Mars"
[4]=>string(7) "Jupiter"
[5]=>string(6) "Saturn"
[6]=>string(6) "Uranus"
[7]=>string(7) "Neptune"
}

The numbers [0] to [7] are the key index values corresponding to each piece of string information stored in the array. You can retrieve string information by calling its key. Supposing you will need to retrieve the planet “Jupiter”, the index key is 4:

<?php
var_dump($planets[4]);
?>
<?php
var_dump($planets[4]);
?>

There are also “associative arrays”, which are useful if you do not use a sequential numerical key index for your string elements. For example:

<?php
//Example1. Associative array of a person and its favorite pet
$favoritepet=array("Mary"=>"Dog","John" =>"Snakes","Paul"=>"Centipede","Peter"=>"Cat");
var_dump($favoritepet);
//Example2. Associative array of a person and its weight in kilos
$weight=array("Mary"=>50,"John" =>60,"Paul"=>80,"Peter"=>71);
var_dump($weight);
?>

Below is the output of the above associative array:

Example1:

array(4) {
["Mary"]=>string(3) "Dog"
["John"]=>string(6) "Snakes"
["Paul"]=>string(9) "Centipede"
["Peter"]=>string(3) "Cat"
}

Example2:

array(4) {
["Mary"]=>int(50)
["John"]=>int(60)
["Paul"]=>int(80)
["Peter"]=>int(71)
}

{mospagebreak title=Common Array String Functions}

1.) count()= This is a function that can be used to count all elements that present in an array. For example:

<?php
$nameofgirl= array("Amanda","Jenna","Elizabeth");
echo "The number of girl names in the array is ".count($nameofgirl);
?>

The above result is 3. There is a similar function to count() that produces the same result known as the sizeof() function.

2.) array_push() = this is used when inserting/adding new elements to an existing array. Supposing you will add the following names to the $nameofgirl array variable earlier:

a.) Linda
b.) Jenny
c.) Anna

<?php
$nameofgirl=array();
$nameofgirl= array("Amanda","Jenna","Elizabeth");
//add new girl games to the existing array
array_push($nameofgirl, "Linda", "Jenny","Anna");
var_dump($nameofgirl);
?>

This is the output (take note that the new elements added are pushed to the end of the array):

array(6) {
[0]=> string(6) "Amanda"
[1]=> string(5) "Jenna"
[2]=> string(9) "Elizabeth"
[3]=> string(5) "Linda"
[4]=> string(5) "Jenny"
[5]=> string(4) "Anna"
}

Another way to add elements in the array is by equating the string to be inserted with the array variable:

$arrayvariable[]="String to be inserted to the array"

Illustration: Add the five letters to an existing array of alphabetical letters.

<?php
$fiveletters=array("d","e","f","e","f");
$existingarray=array("a","b","c");
//Read the five letters array by looping on it and then adding it to the existing array
foreach ($fiveletters as $value) {
$existingarray[]=$value;
}
//dump the updated elements in $existing array
var_dump($existingarray);
?>

This is the result:

array(8) {
[0]=>string(1) "a"
[1]=>string(1) "b"
[2]=>string(1) "c"
[3]=>string(1) "d"
[4]=>string(1) "e"
[5]=>string(1) "f"
[6]=>string(1) "e"
[7]=>string(1) "f"
}

3.) in_array() = check if a specific string is present in an array. Example: Supposing you will check if the name “Linda” is present in the $nameofgirl array.

<?php
$nameofgirl=array();
$nameofgirl= array("Amanda","Jenna","Elizabeth");
array_push($nameofgirl, "Linda", "Jenny","Anna");
//check if name "Linda" is present in the array
if (in_array("Linda",$nameofgirl)) {
echo "Yes the name Linda is found on the array";
} else {
echo "Sorry but the name Linda is not on the array";
}
?>

The above code will return “Yes the name Linda is found in the array”.

4.) array_unique() = removes duplicate values on the array. Example:

Supposing you have an array of colors:

<?php
//Supposing you have an array of colors, red is a duplicate
$fivecolors=array("blue","red","yellow","red","magenta");
var_dump($fivecolors);
?>

Below is the dump of this array (take note of the index key value of each string element):

array(5) {
[0]=>string(4) "blue"
[1]=>string(3) "red"
[2]=>string(6) "yellow"
[3]=>string(3) "red"
[4]=>string(7) "magenta"
}

Now remove the duplicate, using array_unique:

<?php
$fivecolors=array("blue","red","yellow","red","magenta");
//remove the duplicates in the array
$unique=array_unique($fivecolors);
//output to browser
var_dump($unique);
?>

This is the dump results of the array_unique function. You will notice that the array element with key index 3 is gone because it is a duplicate.

array(4) {
[0]=>string(4) "blue"
[1]=>string(3) "red"
[2]=>string(6) "yellow"
[4]=>string(7) "magenta"
}

{mospagebreak title=PHP asort, array_pop, array_merge, and array_search Functions}

5.) array_values() = this will be used to reset any gaps in the indexes caused after implementation of array_unique. In the previous example, you will notice that the indexes are 0,1,2 and 4 (3 is removed because it is a duplicate). You can reset it back to 0,1,2,3,4 using array_values() function:

<?php
$fivecolors=array("blue","red","yellow","red","magenta");
$unique=array_unique($fivecolors);
//reset the numbering of index to the correct sequence, removing any gaps
$resettedindex= array_values($unique);
//output to browser
var_dump($resettedindex);
?>

The following is the output:

array(4) {
[0]=> string(4) "blue"
[1]=> string(3) "red"
[2]=> string(6) "yellow"
[3]=> string(7) "magenta"
}

The key indexes are now in the correct sequence (0,1,2,3).

6.) array_change_key_case() = this function can be used to produce a uniform casing in all strings present in the array. Sometimes you will be processing string elements in an array that does not have uniform casing distribution (for example, strings with both upper and lowercases). If you need to make all casing “upper case” or “lower case”; then you can use this function.

Example:

<?php
$mixedcase=array("bLuE"=>1,"RED"=>2,"Yellow"=>3,"mAgENTA"=>4); //convert all strings in the array to UPPER CASE $uppercase= array_change_key_case($mixedcase, CASE_UPPER); //dump the array var_dump($uppercase); ?>

This is the output:

array(4) {
["BLUE"]=>int(1) ["RED"]=>int(2) ["YELLOW"]=>int(3) ["MAGENTA"]=>int(4) }

Note: If you do not specify CASE_UPPER, the default is lowercase.

7.) array_count_values = this will return the frequency of occurrences of elements in an array. Example:

<?php
$fivecolors=array("blue","red","yellow","red","magenta");
//return the frequency of occurrences
$frequency=array_count_values($fivecolors);
var_dump($frequency);
?>

This will return the following result:

array(4) {
["blue"]=>int(1)
["red"]=>int(2)
["yellow"]=>int(1)
["magenta"]=>int(1)
}

You may have noticed that the var_dump result is an associative array. To extract the specific frequency of occurrence – for example the red color:

<?php
$fivecolors=array("blue","red","yellow","red","magenta");
$frequency=array_count_values($fivecolors);
//return the frequency of occurrence for red color only
echo $frequency["red"];
?>

8.) array_search = this will search the given string in the array variable and return it if the index key number is found. Example:

<?php
$fivecolors=array("blue","red","yellow","magenta");
//Search the color blue and return the key
$key = array_search('blue', $fivecolors);
echo $key;
?>

The result is 0 because blue is the first element in the array. Another example:

<?php
$fivecolors=array("blue","red","yellow","magenta");
//Search the color white and return the key
$key = array_search('white', $fivecolors);
echo $key;
?>

The result is False/Null or 0 logic because white color is not included in the array. Bear in mind that 0 can be a result of two possible scenarios; the first one is that it did exist in the array and found on the first element. The second scenario is when array_search failed to find the string in the array, which in some logic can be evaluated to 0/False or null. To avoid this type of problem, you might need to test first if the string really did exist in the array by using an in_array() function.

<?php
$fivecolors=array("blue","red","yellow","red","magenta");
//Search the color white and return the key
//Check first if white color is indeed present in the array
if (in_array("white",$fivecolors)) {
//white is present in the array, now extract the key
$key = array_search('white', $fivecolors);
echo $key;
} else {
//white is not present in the array.
echo "The key does not exist for this color";
}
?>

9.) asort = this will sort the string elements found in the array variable alphabetically and maintain the corresponding index.

Example of array string elements not being sorted:

<?php
$favoritebands=array("Mary"=>"Nirvana","John" =>"Metallica","Paul"=>"Beatles","Peter"=>"Who","Alice"=>"Greenday","Chris"=>"Black Sabbath");
foreach ($favoritebands as $key => $val) {
echo "$key = $val<br />";
}
?>

This is the result (not sorted):

Mary = Nirvana
John = Metallica
Paul = Beatles
Peter = Who
Alice = Greenday
Chris = Black Sabbath

Supposing you will sort the array elements in terms of favorite band names:

<?php
$favoritebands=array("Mary"=>"Nirvana","John" =>"Metallica","Paul"=>"Beatles","Peter"=>"Who","Alice"=>"Greenday","Chris"=>"Black Sabbath");
//sort the string elements in the array while maintaining index association
asort($favoritebands);
foreach ($favoritebands as $key => $val) {
echo "$key = $val<br />";
}
?>

This is now the sorted result:

Paul = Beatles
Chris = Black Sabbath
Alice = Greenday
John = Metallica
Mary = Nirvana
Peter = Who

10.) array_merge = combines the elements of two or more arrays. Example:

<?php
$fivecolors=array("blue","red","yellow","magenta");
$threecolors=array("white","black","green");
//Merge the above two arrays
$eightcolors=array_merge($fivecolors,$threecolors);
var_dump($eightcolors);
?>

Result:

array(7) {
[0]=>string(4) "blue"
[1]=>string(3) "red"
[2]=>string(6) "yellow"
[3]=>string(7) "magenta"
[4]=>string(5) "white"
[5]=>string(5) "black"
[6]=>string(5) "green"
}

11.) array_pop = pop out the last element in the array. This is useful if you need to remove the last element when updating an array. Example:

<?php
$animals=array("bear","lion","cheetah","tiger","wolf");
//pop out last element
$pop_out = array_pop($animals);
//show pop off element
var_dump($pop_out);
//output updated animals array
var_dump($animals);
?>

Output for popping out the last element:

string(4) "wolf"

Output for updated animals array (the wolf is gone because its pop off from the array):

array(4) {
[0]=>string(4) "bear"
[1]=>string(4) "lion"
[2]=>string(7) "cheetah"
[3]=>string(5) "tiger"
}
[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan