0

Given this two-dimensional array, each element has two indexes – row and column.

<?php $shop = array( array("rose", 1.25 , 15), array("daisy", 0.75 , 25), array("orchid", 1.15 , 7) ); ?> 

Are these my only two options for extracting the data from the array, using row and column indexes?

<?php echo "<h1>Manual access to each element</h1>"; echo $shop[0][0]." costs ".$shop[0][1]." and you get ".$shop[0][2]."<br />"; echo $shop[1][0]." costs ".$shop[1][1]." and you get ".$shop[1][2]."<br />"; echo $shop[2][0]." costs ".$shop[2][1]." and you get ".$shop[2][2]."<br />"; echo "<h1>Using loops to display array elements</h1>"; echo "<ol>"; for ($row = 0; $row < 3; $row++) { echo "<li><b>The row number $row</b>"; echo "<ul>"; for ($col = 0; $col < 3; $col++) { echo "<li>".$shop[$row][$col]."</li>"; } echo "</ul>"; echo "</li>"; } echo "</ol>"; ?> 

2 Answers 2

3
foreach($shop as $items){ echo $items[0]." costs ".$items[1]." and you get ".$items[2]."<br />"; } 

foreach seems more simple for me, plus it would handle if your key are not numeric like

array( 'foo' => array("rose", 1.25 , 15), 'bar' => array("daisy", 0.75 , 25), 'foobar' =>array("orchid", 1.15 , 7) ); 

personally I avoid to use for in PHP because it's less flexible then foreach in most case.

Sign up to request clarification or add additional context in comments.

Comments

0

You could also use

foreach($shop as $shoprow)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.