0

I have this array

Array
(
    [result] => Array
        (
            [status] => nok
            [reason] => Character not found.
        )

    [code] => 404
    [content_type] => application/json;charset=utf-8
)

I want to check the [status], if it is "nok" it should appear "Match found".

My code:

$info = $r['result']['status'];
if (in_array("nok", $info))
  {
  echo "Match found";
  }
else
  {
  echo "Match not found";
  }
?>
5
  • $r['result']['status'] this is not an array . u can chk like if($info == 'nok') Commented Jun 11, 2016 at 19:59
  • if (in_array("nok", $info)){ needs to be if ($info === "nok"){ Commented Jun 11, 2016 at 20:00
  • $r['result']['status'] this is not array this is a key of an array. Commented Jun 11, 2016 at 20:00
  • or if (in_array("nok", $r['result'])){ you can use this too Commented Jun 11, 2016 at 20:01
  • if (in_array("nok", $info)){ needs to be if ($info === "nok"){ or if (in_array("nok", $r['result'])){ you can use this too Commented Jun 11, 2016 at 20:02

4 Answers 4

1

the function in_array check if the value exists in an array, you don't give an array but a string.

You have two options:

change you code to this:

if (isset($r['result']) && in_array("nok", $r['result'])) { //add isset to not raise a warning when it doesn't exists

Or if the result is always the same you can do this:

if (isset($r['result']['status']) && $r['result']['status'] === 'nok') {   //add isset to not raise a warning when it doesn't exists
Sign up to request clarification or add additional context in comments.

Comments

0

In your case:

 $r['result']['status'] 

is not an array but a string.

So you can ask for:

if(in_array("nok", $r['result']))

or

if($r['result']['status'] == "nok")

2 Comments

That is funny! Less than one minute apart, and the same answer :-)
Easy question! - Everybody wants to answer.
0

$info is not an array, it's a string. Try this instead:

if (in_array("nok", $r['result']))
{
   echo "Match found";
}
else
{
   echo "Match not found";
}

Or

if ($r['result']['status'] == "nok"){

1 Comment

You should use isset so you won't raise a warning when it doesn't exists
0

You don't need to use in_array in this code. in_array searches a linear array for string values... so this is how you would use it:

$arr = array("dog", "cat", "mouse");
if(in_array("mouse", $arr)) echo "Eek, a mouse!";

You can just compare using normal logic since you are comparing a string to a string:

$info = $r['result']['status'];
if ($info == "nok")
  {
  echo "Match found";
  }
else
  {
  echo "Match not found";
  }

1 Comment

Don't use <? since this is not always available: php.net/manual/en/language.basic-syntax.phptags.php

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.