1

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

1
  • 1
    Put an if condition with array_key_exists before running the foreach. Commented Sep 29, 2015 at 8:46

2 Answers 2

2

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);   
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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

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.