Hertus
Hertus

Reputation: 147

Search value "in_array"

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";
  }
?>

Upvotes: 0

Views: 218

Answers (4)

John Proestakes
John Proestakes

Reputation: 313

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";
  }

Upvotes: 0

Perry
Perry

Reputation: 11700

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

Upvotes: 1

Andreas
Andreas

Reputation: 23958

$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"){

Upvotes: 0

Thomas Krcal
Thomas Krcal

Reputation: 97

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")

Upvotes: 0

Related Questions