3 Ways to Loop Through an Array in PHP

Looping through arrays to display data or to do something with data elements is a common task in PHP. In this post, I will introduce 3 ways to loop through an array.

Use foreach

Example array:

$phoneBrands = array(
	'apple' => array('Apple', 'iPhone'),
	'samsung' => array('Samsung', 'Galaxy Note'),
	'huawei' => array('Huawei', 'P30'),
	'xiaomi' => array('Xiaomi', 'Redmi Note 7'),
);

The foreach construct is the most common way to iterate over arrays.

//with $key: current element's key is assigned to variable $key
foreach($phoneBrands as $key => $brand){
	var_dump($key);
	var_dump($brand);
}

Result

string(5) "apple"
array(2) { [0]=> string(5) "Apple" [1]=> string(6) "iPhone" } 
string(5) "samsung" 
array(2) { [0]=> string(7) "Samsung" [1]=> string(11) "Galaxy Note" } 
string(5) "hauwei" 
array(2) { [0]=> string(6) "Huawei" [1]=> string(3) "P30" } 
string(5) "xiaomi" 
array(2) { [0]=> string(6) "Xiaomi" [1]=> string(12) "Redmi Note 7" }  
//without $key
foreach($phoneBrands as $brand){
	var_dump($brand);
}

Result:

array(2) { [0]=> string(5) "Apple" [1]=> string(6) "iPhone" } 
array(2) { [0]=> string(7) "Samsung" [1]=> string(11) "Galaxy Note" } 
array(2) { [0]=> string(6) "Huawei" [1]=> string(3) "P30" } 
array(2) { [0]=> string(6) "Xiaomi" [1]=> string(12) "Redmi Note 7" }  

Use for loop

$phoneBrands = array(
	array('Apple', 'iPhone'),
	array('Samsung', 'Galaxy Note'),
	array('Huawei', 'P30'),
	array('Xiaomi', 'Redmi Note 7'),
);
for ($i = 0; $i < count($phoneBrands); $i++) {	
    echo $phoneBrands[$i][0].' - '.$phoneBrands[$i][1].'<br>';
}

Result

Apple - iPhone
Samsung - Galaxy Note
Huawei - P30
Xiaomi - Redmi Note 7 

Use array_map()

array_map() function applies the callback to the elements of the given arrays. It is not a common way to loop through data but can be used to manipulate data in an array in some cases.

$phoneBrands = array(
	array('Apple', 'iPad'),
	array('Samsung', 'Galaxy S'),
	array('Huawei', 'P40'),
	array('Xiaomi', 'Mi Note'),
);
array_map('displayBrand', $phoneBrands);
function displayBrand($brand){
	echo $brand[0].' has '.$brand[1].'<br>';
}

Result

Apple has iPad
Samsung has Galaxy S
Huawei has P40
Xiaomi has Mi Note 

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close