10

I've got an array with multiple person-objects in it, this objects look like this:

id: 1,
name: 'Max Muster',
email: 'max.muster@example.com',
language: 'German'

Now, I've got objects in another array, which doesn't look exactly the same:

id: 1,
name: 'Max Muster',
email: 'max.muster@example.com',
language: 'de'

I've got a foreach-loop to loop through array 2 and check if the objects exists in array 1.

foreach($array2 as $entry) {
    if(existsInArray($entry, $array1)) {
        // exists
    } else {
        // doesn't exist
    }
}

Is there a function to check (like my existsInArray()), if my object exists in the array? I just need to check, if the object-id exists, other attributes doesn't matter.

TheBalco
  • 395
  • 1
  • 3
  • 25

4 Answers4

19

Use the object IDs as keys when you put the objects in the array:

$array1[$object->id] = $object;

then use isset($array1[$object->id]) to check if the object already exists in $array:

if (isset($array1[$object->id])) {
    // object exists in array; do something
} else {
    // object does not exist in array; do something else
}
axiac
  • 68,258
  • 9
  • 99
  • 134
  • this looks like it checks by index, but isn't index arbitrary? How does this work? – Urasquirrel Sep 14 '20 at 22:42
  • 1
    [PHP Arrays](https://www.yphp.net/manual/en/language.types.array.php) are, in fact, maps/hashes/dictionaries. They associate a numeric or string key to a value of any type. The OP has two sets of objects identified by their `id` attributes. The answer suggests to put the first set of objects in an array and use the `id` as key. When the second set of objects is processed, use the object `id` to find the object with the same `id` in the array. By using the `id` as key (and not a numeric key generated automatically), the object can be identified without scanning the entire array. – axiac Sep 15 '20 at 05:40
4

It does not, but you can write it:

function existsInArray($entry, $array) {
    foreach ($array as $compare) {
        if ($compare->id == $entry->id) {
            return true;
        }
    return false;
}
wogsland
  • 9,106
  • 19
  • 57
  • 93
0
foreach($array2 as $entry) {
    if(in_array($entry, $array1)) {
        // exists
    }  else {
    // doesn't exist
    }
}

Use in_array to check if that particular object exists in the array

User2403
  • 317
  • 1
  • 5
0

Use in_array

if(in_array($object, array)) {
   //exists
} else {
   //does not exist
}