How to remove value from array in PHP?
In this post, the function will remove the element from an array by value, we can use the combination of array_search()
and unset()
functions in PHP.
1. Code:
<?php function removeValueFromArray($delVal, $array){ $i = 0; $lenght = count($array); for($i = 0; $i < $lenght; $i++){ if($delVal == $array[$i]){ unset($array[$i]); } } return $array; } $array = array(1, 2, 3, 5, 3, 1); print_r($array ); echo "<br>"; print_r(removeValueFromArray(1, $array )); ?>
2. Example:
Input:
$str = array(1, 2, 3, 5, 3, 1); removeValueFromArray(1, $str);
Output:
Array ( [1] => 2 [2] => 3 [3] => 5 [4] => 3 )