PHP count and display items in a 2D (multidimensional) array
This is a short snippet about counting elements in array and displaying all items. Below is a sample 2D (two dimensional) array. Columns represents respectively: SKU, NAME and PRICE.
$products = array(
array('TIR', 'Tires', 100),
array('OIL', 'Oil', 10),
array('SPK', 'Spark plugs', 4),
array('WPR', 'Wiper blade', 3)
);
To display for example Tires we will echo:
echo $products[0][1];
It would be silly to display all array elements in this manner so we are going to use two for loops, but before that we are going to count array elements:
$array_elements = count($products); #return 4 $all_array_elements = count($products, COUNT_RECURSIVE); #return 16 $single_elements_2D = ($all_array_elements - $array_elements) / $array_elements; #return (16-4)/4 = 3
Now the two for loops:
for ($row=0; $row < $array_elements; $row++) {
for ($column=0; $column < $single_elements_2D; $column++) {
echo " | " . $products[$row][$column];
}
echo " |<br>";
And that’s it. You can try to add or remove some array elements and you’ll see that it works. Cheers!


Leave a Reply