How can I filter an array in PHP to retrieve the elements that are not presented in the array?

 I am currently working on a specific task that is related to filtering an array in PHP for retrieving the elements that are not present in another array by using the “not in array” concept. How can I do so? 

Answered by Dhananjay Singh

 In the context of web development, if you want to filter an array in PHP to retrieve the elements that are not present in another array, then you can use the “array_diff” function. Here is the example given which showcases the process:-

// Original array
$originalArray = [1, 2, 3, 4, 5];
// Array containing values to be excluded
$valuesToExclude = [2, 4];
// Filter the original array to exclude values present in $valuesToExclude
$resultArray = array_diff($originalArray, $valuesToExclude);
// Output the result
Print_r($resultArray);

In this above example the function “array_diff” would use in comparing the values of “$originalArray” with the values in “$ValuesToExclude” and would return an array that contains the values from “$OriginalArray” which are not presented in “$valuesToExclude”

Array
(
    [0] => 1
    [2] => 3
    [4] => 5
)

This result array would now contain the elements which are not presented in the array called “$valuesToExclude”.



Your Answer

Interviews

Parent Categories