2

I am learning php, while practising I had an issue. I have created a multidimensional array with item values and am using a for loop to print those values but I am getting

Error: undefined offset

The array format is associative.

Requirement:

1) print all values using for loop/foreach loop

2) if any associative array is empty avoid that

3) check whether it is array or single value like some values again have their own array

$item_list=array();  //multidimensional array with associative values
echo '<pre>';print_r($item_list);

Array
(
    [total_price] => 1200
    [item_1] => Array
        (
            [item_name1] => xyz
            [item_price1] => 100.00

        )

    [item_2] => Array
        (
            [item_name2] => abc
            [item_price2] => 200.00

        )


    [item_3] => 
    [item_4] => Array
        (
            [item_name3] => aaa
            [item_price3] => 402.00
        )

)

// code which I have used to echo all values

for ($row = 0; $row < count($item_list); $row++) {
  // if value contain array then go to nested for loop else print direct value
  echo "<ul>";
  for ($col = 0; $col < count($item_list[$row]); $col++) {

    //echo "<li>".$item_list[$row][$col]."</li>";
    echo "<li>".array_values($item_list[$row])[$col]."</li>";

  }
  echo "</ul>";
}
3
  • a recursiveArrayIterator might suit your needs Commented Oct 27, 2019 at 7:26
  • No, ijust want to print values according to their group for example item_1: its name,price for item_2 its name ,price Commented Oct 27, 2019 at 7:26
  • can you please correct my code so that it will print all values Commented Oct 27, 2019 at 7:28

1 Answer 1

1

Since your array is associative, you can't access the values using a numeric index in a for loop. Instead, use a foreach loop over the elements:

foreach ($item_list as $key => $item_details) {
    if (is_array($item_details)) {
        echo "$key:\n";
        foreach ($item_details as $name => $value) {
            echo "\t$name: $value\n";
        }
    }
    else {
        echo "$key: $item_details\n";
    }
}

Output:

total_price: 1200
item_1:
    item_name1: xyz
    item_price1: 100
item_2:
    item_name2: abc
    item_price2: 200
item_3: 
item_4:
    item_name3: aaa
    item_price3: 402

Demo on 3v4l.org

Note it's not really clear what you're trying to achieve formatting wise, so I've just left the output in simple line format. It would be fairly easy to add <ul>/<li> structure to this.

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

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.