Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an object exists in an array

Tags:

arrays

object

php

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

id: 1,
name: 'Max Muster',
email: '[email protected]',
language: 'German'

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

id: 1,
name: 'Max Muster',
email: '[email protected]',
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.

like image 973
TheBalco Avatar asked May 30 '16 11:05

TheBalco


1 Answers

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
}
like image 52
axiac Avatar answered Sep 20 '22 07:09

axiac