enriqg9
enriqg9

Reputation: 1507

Check if object is in array

I have the code below to check if the object is inside the array, but in_array() is always true and I end up with the exact same object inside the array multiple times.

if(!in_array($lang, $lang_array, true)){
  $languages .= $lang . ", ";
  $lang_array[] = $lang;
}

I end up with something like this:

array(3) {
    [0]=> object(SimpleXMLElement)#389 (1) {
        ["@attributes"]=> array(1) {
            ["Code"]=> string(1) "E"
        }
    }
    [1]=> object(SimpleXMLElement)#388 (1) {
        ["@attributes"]=> array(1) {
            ["Code"]=> string(1) "E"
        }
    }
    [2]=> object(SimpleXMLElement)#387 (1) {
        ["@attributes"]=> array(1) {
            ["Code"]=> string(1) "E"
        }
    }
}

Upvotes: 1

Views: 282

Answers (2)

outis
outis

Reputation: 77420

in_array requires an array scan for each call. Better is to make use of string keys. Since the objects are convertible to strings, you can use the string value as keys if the string value is unique. Arrays work well for sets of integers or strings, with the keys as elements, since keys can't be repeated.

$langs[(string)$lang] = $lang;
...
$languages = implode(', ', $langs);

Upvotes: 0

Phil
Phil

Reputation: 164871

If all you're interested in is the Code attribute, why not simply store that then run the array through array_unique?

$lang_array = [];
foreach(...) {
    $lang_array[] = (string) $lang['Code'];
}
$lang_array = array_unique($lang_array);
$languages = implode(', ', $lang_array);

Upvotes: 1

Related Questions