Check array keys

Asked

Viewed 413 times

0

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

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

I made a bow:

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

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

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

  • 1

    I’m running out of time to respond, but to help in case no one shows up, search by Flatten array.

  • Gives a return; after printing it will stop at the first exit;

  • @Ivanferrer Can’t Give Re-turn; because if I give it it doesn’t continue to list the other records who comes from $Row...

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 so:

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

If it is to check that the collection key itself is equal to the value, it would be so:

  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 needing the loop, this is so:

if (array_key_exists($row['chave'], $chaves)) {
  echo 'ok, é igual';
} else {
  echo 'ok, não é igual';
}
  • I get it, the problem is that so, there is a need to have a loop because the array may be larger than 2, and I would need to analyze every $Row return line... Understands?

  • I thought using array_exists() even worked, but it keeps writing if there is a value inside the array and if there is no tbm... http://pastebin.com/feUB6idt (it was like this)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.