1

This is my array animals:

array(5) {
  [0]=>
  array(3) {
    ["number"]=>
    string(3) "123"
    ["cat"]=>
    string(4) "fred"
    ["dog"]=>
    string(3) "ted"
  }
  [1]=>
  array(3) {
    ["number"]=>
    string(3) "456"
    ["cat"]=>
    string(4) "todd"
    ["dog"]=>
    string(4) "jane"
  }
  [2]=>
  array(3) {
    ["number"]=>
    string(3) "789"
    ["cat"]=>
    string(3) "sam"
    ["dog"]=>
    string(3) "bob"
  }
  [3]=>
  array(1) {
    ["city"]=>
    string(7) "atlanta"
  }
  [4]=>
  array(1) {
    ["farm"]=>
    string(7) "johnson"
  }
}

I want to detect the following:

For each array that contains number I need to find out if cat and dog exist.

This is my try:

  foreach($animals as $row) {
       if (array_key_exists('number',$row)){                
          if(empty($row['dog'])){
             echo "dog missing";
          }
          if(empty($row['cat'])){
             echo "cat missing";
          }
       }
    }

So if I for example delete in my file fred, ted and jane my result is:

cat is missing
dog is missing
dog is missing

But I need to know more specific which cat or dog is missing. So the result I wish to have is:

cat is missing in number 123
dog is missing in number 123
dog is missing in number 456

My problem is that I do not know how to get the connection from the animal to the number.

3
  • 1
    Take a look at phps array-walk() function: php.net/manual/en/function.array-walk.php Commented Nov 11, 2015 at 10:42
  • 4
    echo "dog is missing in number ".$row['number']; Commented Nov 11, 2015 at 10:43
  • 1
    You might want to use array_key_exists() or isSet() instead of the empty() because of false positives (empty(0) returns TRUE) Commented Nov 11, 2015 at 10:44

1 Answer 1

1

Can't you just add it to the echo? Like:

foreach($animals as $row) {
       if (array_key_exists('number',$row)){                
          if(empty($row['dog'])){
             echo "dog missing in number ".$row["number"];
          }
          if(empty($row['cat'])){
             echo "cat missing in number ".$row["number"];
          }
       }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

oh yes, this is true.. I was thinking to complicated :D
I was two mins faster :)

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.