PHP - How do I filter array if the value of the elements are equal to zero?

Hello all,

I am the absolute beginner in PHP. I have one problem that I do not know how to solve. I have an array that should I filter:

[[1,1,1,0],[1,1,1,1],[1,0,0,0],[1,0,0,1],[1,0,1,0]]

I need to filter it by expelling all elements in which the second and third values are equal to 0.
Example:

[[1,1,1,0],[1,1,1,1],[1,0,1,0]]

I really have no idea where to start. Can somebody help me?

You could use the array_filter function, supplying it with a custom function which finds the zeros in those positions.

<?php
 $array = [[1,1,1,0],[1,1,1,1],[1,0,0,0],[1,0,0,1],[1,0,1,0]] ; // This is your original array
 
function zeros($array){		// This function will check the second (1) and third (2) values of the sub-arrays to see if they equal 0
		if(($array[1] === 0) && ($array[2] === 0)){ return false ;} // if both are 0, return false to discard them
		else{ return true ;}		// Otherwise retuen true to keep them
}
	
$filtered = array_filter($array, "zeros") ; // This function will apply the "zeros" function to each array value. if the function returns false the value is removed from the resulting array
	
// See the results...
echo "Original Array:-\n";
var_dump($array);
echo "Filtered Array:-\n";
var_dump($filtered);
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.