W3docs

PHP : Remove object from array

Here is an example of how to remove an object from an array of objects in PHP:

Here is an example of how to remove an object from an array of objects in PHP:

Example of removing object from an array in PHP

<?php
$objectToRemove = new stdClass();
$objectToRemove->id = 1;
$array = [$objectToRemove, new stdClass(), new stdClass()];

$key = array_search($objectToRemove, $array, true);
if ($key !== false) {
  unset($array[$key]);
  $array = array_values($array);
  echo "Object removed from the array!";
} else {
  echo "Object not found in the array.";
}
?>

In this example, an array of three stdClass objects is created, with the first being the target object. The array_search function is used with strict comparison (true) to locate the exact instance of $objectToRemove. If found, unset removes it, and array_values reindexes the array to maintain sequential numeric keys. A message confirms the removal. If not found, a message indicates it wasn't found.

Note on object comparison: In PHP, objects are compared by reference (identity) by default. Two separate new stdClass() instances will never match, even if they contain identical properties. To compare by value, iterate through the array and compare specific properties (e.g., $obj->id === $target->id).

You can also use array_filter to remove an object from an array.

Example of using array_filter to remove object from an array in PHP

<?php
$objectToRemove = new stdClass();
$objectToRemove->id = 1;
$array = [$objectToRemove, new stdClass(), new stdClass()];

$originalCount = count($array);
$array = array_filter($array, function ($obj) use ($objectToRemove) {
  return $obj !== $objectToRemove;
});

if (count($array) < $originalCount) {
  echo "Object removed from the array!";
} else {
  echo "Object not found in the array.";
}
?>

In this example, an array of three stdClass objects is created, with the first being the target. array_filter iterates through the array, keeping only objects that are not identical to $objectToRemove. The original array count is stored before filtering. If the filtered array's count is less than the original, an object was removed and a success message is displayed. Otherwise, the object was not found.