katie hudson
katie hudson

Reputation: 2893

PHP foreach loop on multi dimensional array

having a bit of difficulty with a multi-dimensional array. I have shortened it, but the array looks like this

array(192) {
    ["count"]=> int(191)
        [0]=>array(124) {
            [11]=>string(10) "usnchanged"
                ["homemta"]=>array(2) {
                  ["count"]=>int(1)
                  [0]=>string(206) "Some String"
                }
            [12]=>string(7) "homemta"
                ["proxyaddresses"]=>array(2) {
                  ["count"]=>int(1)
                  [0]=>string(46) "SMTP:[email protected]"
                }
        }
    }
}

I am trying to get the email addresses which will be listed under proxyaddresses. What I am doing at the moment is the following:

for($i=0; $i<$data["count"]; $i++) {
    foreach($data[$i]["proxyaddresses"] as $object) {
        print_r($object);   
    }
}

This gets me the data I need, but inbetween all the data I get a lot of warnings like

Notice: Undefined index: proxyaddresses in index.php on line 88

Warning: Invalid argument supplied for foreach() in index.php on line 88

So I presume it is not liking something. How would I properly do the loop based on the above array structure?

Thanks

Upvotes: 1

Views: 82

Answers (2)

Ranjana
Ranjana

Reputation: 815

It's because proxyaddresses element is not present for each loop. You have to check if it's set or not to avoid warning by using php isset() function.

for($i=0; $i<$data["count"]; $i++) {
  if(isset($data[$i]["proxyaddresses"])){
    foreach($data[$i]["proxyaddresses"] as $object) {
      print_r($object);   
    }
  }
}

Upvotes: 2

Halayem Anis
Halayem Anis

Reputation: 7785

for($i=0; $i<$data["count"]; $i++) {
    if(!isset($data[$i]["proxyaddresses"])) continue;
    foreach($data[$i]["proxyaddresses"] as $object) {
        print_r($object);   
    }
}

Upvotes: 1

Related Questions