1

I am still trying to understand how the php foreach loop works with accessing certain parts of it. I have an array setup like this:

$product = Array
(
    [SX- Light weight] => Array
        (
            [bronze] => 4
            [silver] => 5
            [gold] => 6
        )

    [SS- Light weight] => Array
        (
            [bronze] => 4
            [silver] => 5
            [gold] => 6
        )
)

I have a foreach loop set up like so:

foreach ($product as  $name => $value) {
        # code...
        echo '<option value="'.$name.'">'.$name.'</option>'; 

    }

That spits me out $name as "SX- Light weight" for instance. How would I access the [bronze] number 4?

3
  • 1
    to access the sub array elements, you'll need to use another foreach loop, or just access them directly thru $value['bronze'], etc. Commented Feb 8, 2016 at 22:56
  • * You should put in indices of your arrays in quotation marks. Not doing so will work but issue warnings. Commented Feb 8, 2016 at 23:10
  • It is never beneficial to duplicate an option tag's text as its value attribute value. You can ALWAYS safely omit this html markup bloat and rely solely on the text value. No javascript or form submission processes will be affected by writing leaner option markup in this way. Commented Aug 29, 2022 at 22:09

4 Answers 4

2
foreach ($product as $name => $value) {
    // display 'bronze' index's value (assuming it is defined)
    echo 'For product '.$name.', bronze value = '.$value['bronze'];
}

You may want as well to display all the "metals" using a sub-loop:

foreach ($product as $name => $value)
{
  echo "For product ".$name.", values are: \n";

  // assuming $value is an associative array
  foreach ($value as $metal => $number)
  {
    echo "- ".$metal.": ".$number."\n";
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

It may help your understanding to visualize this two-dimensional array in two dimensions, sort of like a spreadsheet.

                  [bronze][silver][gold]
[SX- Light weight]   4       5       6
[SS- Light weight]   4       5       6

The foreach loops over the rows. This means that in

foreach ($product as  $name => $value) {

the $value is not a single value, it is a row, an array containing the values of the bronze, silver, and gold columns. So in the first iteration of this loop, for example, $value will contain

array('bronze' => 4, 'silver' => 5, 'gold' => 6)

You can iterate over each column in the row and do something with those values by using another foreach, but if you just need to access a specific column, you can use its key to specify which one you want, like this:

echo $value['bronze'];

Thinking of the contents of a two-dimensional array as rows and columns is a pretty common visualization. In fact, in PHP 5.5+ there is the array_column function, that allows you to pull all of the values from a specific column into a new array.

$bronze = array_column($product, 'bronze');  // for example.

Obviously if the array goes beyond two dimensions, this visualization becomes less useful.

Comments

0

Reference it from the value.

foreach ($product as  $name => $value) {
    echo $value['bronze']; 
}

Comments

0

Your usage of foreach command to loop through a multidimensional array in PHP will depend on the structure of the array.

For example:

<?php

// Let's build the array structure
$array[1]['name'] = "John";
$array[1]['phone'] = "+1 888 9567834";
$array[2]['name'] = "Doe";
$array[2]['phone'] = "+44 32 5600 673";
$array[3]['name'] = "Robert";
$array[3]['phone'] = "+1 45 5634 0843";
$array[4] = "Maria";


foreach ($array as $key1 => $value)
{
    echo "<br> Value: $key1 Value: $value<br>";

    // If it's an array, let's do another look inside it
    if (is_array($value))
    {
        foreach ($value as $key2)
        {
            echo "---- $key2 <br>";
        }
    }

    // if it's a simple string (non-array), let's print it
    else
    {
        echo "---- $value";
    }
}


?>

Check this article for more about looping through array in PHP.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.