Check array braces

0

Next, I have a saved array value in the $chaves variable as in the example below:

array(2) {
   [0] => array(1) {
      ["chave"] => string(1) "1"
   }
   [1] => array(1) {
      ["chave"] => string(1) "3"
   }
}

I made a loop:

foreach ($chaves as $chave) {
    if (in_array($row['chave'], $chave)) {
       echo 'ok, é igual';
    } else {
       echo 'ok, não é igual';
    }
}

However, it is printing like this "ok, it's okay, it's not the same", but it should print: "ok, it's not the same" when the value is different and "ok, it's the same" when the value is equal.

The idea is to show that it is the same when the key values are the same.

    
asked by anonymous 18.07.2016 / 21:46

1 answer

0

If the idea is to check a key from an external collection and if it is equal to the value, you can do this:

foreach ($chaves as $key => $chave) {
    if ($row['chave'] == $key) {
       echo 'ok, é igual';
    } else {
       echo 'ok, não é igual';
    }
}

If it is to check if the collection key itself is equal to the value, it would look like this:

  foreach ($chaves as $key => $chave) {
        if ($key == $chave) {
           echo 'ok, é igual';
        } else {
           echo 'ok, não é igual';
        }
    }

Now if you want to check the key inside an array, without the need for the loop, it looks like this:

if (array_key_exists($row['chave'], $chaves)) {
  echo 'ok, é igual';
} else {
  echo 'ok, não é igual';
}
    
18.07.2016 / 22:06