简体   繁体   中英

how to unset array which has empty value using php?

How to unset two array value which has zero value...

$array1=Array ( [0] => SL [1] => S [2] => M [3] => L [4] => F ) 
$array2=Array ( [0] => 15 [1] => 22 [2] => 35 [3] => 0 [4] => 0 )

always first array and second array keys are same. i wanna check second array value is empty or not if empty then i need to remove values from both the array

I need output:

Array ( [0] => SL [1] => S [2] => M  ) 
Array ( [0] => 15 [1] => 22 [2] => 35 )

Assuming the index of array1 corresponds to the index of array2, you just need to find the indexes of $array2 whose values are 0. Once you've done that, just unset the elements with the given index from both arrays.

foreach($array2 as $key=>$value){
    if($value === 0){
        unset($array2[$key]);
        unset($array1[$key]);
    }
}
function removeZeroValues($array) {
    foreach ($array as $key => $value) {
        if ($value === 0) {
            unset($array[$key]);
        }
    }

    return $array;
}

$array1 = array("SL", "S", "M", "L", "F");
$array2 = array(15, 22, 35, 0, 0);

$array1 = removeZeroValues($array1);
$array2 = removeZeroValues($array2);

echo "<pre>";
print_r($array1);
print_r($array2);

You can use array_filter,

$array2 = array_filter($array2);
$array1 = array_filter($array1, function($k)use($array2){return isset($array2[$k]);}, ARRAY_FILTER_USE_KEY);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM