简体   繁体   中英

How to find and replace empty values in an array?

for the example, I have an array

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

and I want to find empty array value, and replace it.

[1] => data not found

Non-recursive:

$arr = array(
    0 => array(
        0 => "0",
        1 => "1"
    ),
    1 => "",
    2 => array(
        4 => "4",
        5 => "5",
        7 => "7"
    ),
    3 => array(
        8 => "",
        9 => ""
    )
);

foreach($arr as &$val){
if($val === "" || $val === false || $val === null) $val = "data not found";
}

print_r($arr);

DEMO

Recursive:

function replace_empty_values($arr){
    foreach($arr as &$val){
    if(is_array($val)) $val = replace_empty_values($val);
    else if($val === "" || $val === false || $val === null) $val = "data not found";
    }
return $arr;
}

$arr = array(
    0 => array(
        0 => "0",
        1 => "1"
    ),
    1 => "",
    2 => array(
        4 => "4",
        5 => "5",
        7 => "7"
    ),
    3 => array(
        8 => "",
        9 => ""
    )
);

$arr = replace_empty_values($arr);
print_r($arr);

DEMO

Here is a recursive solution.

$myArray = array(
    0 => array(
        0 => "0",
        1 => "1"
    ),
    1 => "",
    2 => array(
        4 => "4",
        5 => "5",
        7 => "7"
    )
);

function removeEmpty($arr){
    if(is_array($arr)){
        foreach($arr as &$val){
             $val = removeEmpty($val);
        }
        return $arr;
    }
    else {
        if(empty($arr) && $arr != "0") return "data not found";
    }
}

print_r(removeEmpty($myArray));

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