Change language

PHP Removing an element from an array using array_diff ()

|
Examples:
Input: $arr = array (2, 8, 9, 7, 6, 5); $arr = array_diff ($arr, array (9)); Output: Array ([0] = > 2 [1] = > 8 [3] = > 7 [4] = > 6 [5] = > 5) Input: $arr = array ("shubham" , "akshay", "vishal", "sweta"); $arr = array_diff ($arr, array ("akshay")); Output: Array ([0] = > shubham [2] = > vishal [3] = > sweta) 
array_diff() The array_diff() function takes two or more arguments and returns an array containing values ​​from the first array that are not in other arrays.Approach . The idea behind this problem is that we pass two arrays to the array_diff() function as parameters. The first array in the parameter will be the array from which we want to remove the element. The second array will contain the only element that we want to remove from the first array. Finally, we will store the resulting array returned by array_diff() in the input array.The following programs illustrate the above approach:Program 1: $arr = array (2, 8, 9, 7, 6, 5); // returns an array after deletion // array value 9 $arr = array_diff ( $arr , array (9)); print_r ( $arr );  
?>
Output:
Array ([ 0] = > 2 [1] = > 8 [3] = > 7 [4] = > 6 [5] = > 5) 
Program 2:   $arr = array ( " Harsh " , "Nishant" , "Akshay" , "Barun" , "Bikash" ); // returns an array after deletion // value of the Akshay array $arr = array_diff ( $arr , array ( "Akshay" )); print_r ( $arr );  
?>
Output:
Array ([ 0] = > Harsh [1] = > Nishant [3] = > Barun [4] = > Bikash)