php - unset an array with a specfic condition -
basically have array $code
:
array ( [1] => array ( [0] => france [1] => 26422 [2] => 61748 [3] => 698477678 ) [2] => array ( [0] => united states [1] => 545 [2] => 2648 [3] => 55697455 ) [3] => array ( [0] => canada [1] => 502 [2] => 1636 [3] => 15100396 ) [4] => array ( [0] => greece [1] => 0 [2] => 45 [3] => 458 )
i want unset countries $code[$key][1] == 0
tired this:
$code = array_filter($code, function (array $element) { return !preg_match('(0)i', $element[1]); });
but returns countries unless 1 has in $code[$key][1]
0, this:
array ( [1] => array ( [0] => france [1] => 26422 [2] => 61748 [3] => 698477678 ) [2] => array ( [0] => united states [1] => 545 [2] => 2648 [3] => 55697455 )
any how can achieve this? thanks!
without regex:
$code = array_filter($code, function (array $element) { return ($element[1] !== 0); });
with regex (you need use anchors):
$code = array_filter($code, function (array $element) { return !preg_match('/^0$/', $element[1]); });
however, i’ll recommend simple foreach
loop instead of array_filter
:
foreach($code $key => $val){ if($val[1] === 0) unset($code[$key]); }
Comments
Post a Comment