To remove a specific element from an array in PHP, you can use the `unset` function or create a new array excluding the element to be removed.
In this example,
<?php
$numbers = [1, 2, 3, 4, 5];
$indexToRemove = array_search(3, $numbers);
unset($numbers[$indexToRemove]);
$numbers = array_values($numbers);
echo 'Array after removing 3: ';
print_r($numbers);
?>
Array after removing 3: Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 5 )
In this example,
<?php
$colors = ['red', 'green', 'blue', 'yellow'];
$elementToRemove = 'green';
$newArray = [];
foreach ($colors as $color) {
if ($color !== $elementToRemove) {
$newArray[] = $color;
}
}
echo 'Array after removing ' . $elementToRemove . ': ';
print_r($newArray);
?>
Array after removing green: Array ( [0] => red [1] => blue [2] => yellow )
In this tutorial, we learned How to Remove Specific Element from an Array in PHP language with well detailed examples.