1

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"
        }
    }
}
3
  • Those SimpleXMLElement objects all have different object hashes so they are not the same object. Commented Mar 19, 2014 at 4:23
  • @Phil How can I check if the value of the object, in this case "E", is already in an array? Commented Mar 19, 2014 at 4:27
  • "E" is not the value of the object. It is the value of the Code index on the @attributes property of the SimpleXMLElement object. You would need to loop through each item and check it. Commented Mar 19, 2014 at 6:21

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Hmm.. didn't think of it that way, I just converted the property to string while storing it in the array $lang_array[] = (string)$lang["Code"]; and now it works :) thanks for the note.
0

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

2 Comments

Thanks, I did it the other way, the value instead of the key $lang_array[] = (string)$lang["Code"];
@enriqg9: Using it for both would be more performant, as you wouldn't need to use array_unique().

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.