Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php in array returning false when value does exist

Tags:

arrays

php

Simple one here, but hurting ones head.

echo in_array('275', $searchMe);

is returning false. But if I print the array out and then search it manually using my web browser I am able to see that the value exists in the array.

[0] => ExtrasInfoType Object
                (
                    [Criteria] => 
                    [Code] => 275
                    [Type] => 15
                    [Name] => Pen
                )

Extra information. The array has been coverted from an object to an array using

$searchMe = (array) $object;

Would it be because the values are not quoted? I have tried using the following with the in_array function:

echo in_array('275', $searchMe); // returns false
echo in_array(275, $searchMe); // returns error (Notice: Object of class Extras could not be converted to int in)

var_dump of $searchMe

array
  'Extras' => 
    object(Extras)[6]
      public 'Extra' => 
        array
          0 => 
            object(ExtrasInfoType)[7]
              ...
          1 => 
            object(ExtrasInfoType)[17]
              ...
          2 => 
            object(ExtrasInfoType)[27]
              ...
like image 261
JS1986 Avatar asked May 17 '26 00:05

JS1986


1 Answers

One scenario I think that would be helpful.

If the array index that contains the value is 0, the returning value of in_array would be 0. If in our logic, 0 is considered as false, then there will be issues. Avoid this pattern in your code.

like image 128
buddhiv Avatar answered May 19 '26 14:05

buddhiv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!