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.
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):
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);
?>
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):
<?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.