PHP : Remove object from array

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

<?php
$array = [new stdClass(), new stdClass(), new stdClass()];

$objectToRemove = new stdClass();

$key = array_search($objectToRemove, $array);
if ($key !== false) {
  unset($array[$key]);
  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. A new stdClass object is created and stored in the variable $objectToRemove. Then, the array_search function is used to search the $array for the object stored in $objectToRemove. If the object is found, the unset function is used to remove it from the array and a message is displayed indicating that the object has been removed. If the object is not found, a message is displayed indicating that it wasn't found.

You can also use array_filter to remove object from array

<?php
$array = [new stdClass(), new stdClass(), new stdClass()];

$objectToRemove = new stdClass();

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

if (count($array) < count($array) - 1) {
  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. A new stdClass object is created and stored in the variable $objectToRemove. Then, the array_filter function is used to remove all instances of $objectToRemove from $array. The count of the original array and the filtered array is compared and if the count of the filtered array is less than the original array, it means that an object has been removed and a message is displayed indicating that the object has been removed. If the count of the filtered array is equal to the original array, it means that the object was not found and a message is displayed indicating that the object wasn't found.