An array in PHP is actually an ordered map that can hold more than one value at a time.
Table of Contents
Define/Delete an array
An array can be created using the array() language construct.
$names = array(
0 => "Idell Pouros",
1 => "Yasmine Rempel",
2 => "Marco Auer",
3 => "Cyrus Frami",
4 => "Dandre Donnelly",
5 => "Erin O'Connell",
6 => "Bryana Quitzon",
7 => "Kieran Lakin",
8 => "Hudson Gerlach",
);
$users = array(
0 => array(
"username" => "annie40",
"fullname" => "Olaf Kuhn",
"email" => "[email protected]",
"ip_adress" => "82.223.72.171",
),
1 => array(
"username" => "daugherty.zoie",
"fullname" => "Cleo Kerluke",
"email" => "[email protected]",
"ip_adress" => "169.217.32.183",
),
)
To clear an array’s values you can use one of the following method
unset($array);
$array = array();
Check empty array and count
$arr = array(1, 2, 3, 4, 5);
echo empty($arr); //return FALSE
An array’s length can be returned with count()
function.
echo count($users);
Loop through an array
$users = array(
0 => "Brisa Johnson",
1 => "Janessa Bergnaum",
2 => "Blaze Goodwin",
3 => "Khalil Lehner",
4 => "Adrienne Lebsack",
5 => "Mozelle Breitenberg",
);
foreach($users as $key => $user) {
echo $key.': '.$user;
}
for ($i = 0; $i < count($users); $i++) {
echo $users[$i].PHP_EOL;
}
Check if a variable is an array
is_array
checks whether a variable is an array or not.
$arr = array("Java", "Kotlin", "Dot Net");
if (is_array($arr))
echo 'This is an array....';
else
echo 'This is not an array....';
Convert array to string and vice versa
Array to String
$array = array(
'color' => "Green",
'weight' => "0.5kg",
'length' => "100cm",
);
$string = implode(',', $array);
print_r($string);
//output: Green,0.5kg,100cm
String to Array
$string = "Samsung, Apple, Xiaomi, Apple, Huawei";
$array = explode(',', $string);
print_r($array);
//output: Array ( [0] => Samsung [1] => Apple [2] => Xiaomi [3] => Apple [4] => Huawei )
Add elements to an empty array in PHP
$users = array();
$users[] = 'Martin';
array_push($users, 'Rocker');
array_push($users, 'Kentucky', 'Eric', 'Price');
Merge 2 arrays / append one to another
$a1 = array('A', 'B', 'C');
$a2 = array('D', 'E', 'F');
$a = array_merge($a1, $a2);
Compare 2 arrays
// result is TRUE if $a and $b have the same key/value pairs.
$result = ($a == $b);
// result is TRUE if $a and $b have the same key/value pairs in the same order and of the same types
$result = ($a === $b);
Remove duplicate values
$array = array("Samsung", "Apple", "Xiaomi", "Apple", "Huawei");
$result = array_unique($array);
Get min and max values
In 1-dimension array, we can use min() and max() functions to retrieve these values.
$array = array(20, 12, 32, 14, 25);
echo min($array); //output: 32
echo max($array); //output: 12