VikingBlooded
VikingBlooded

Reputation: 859

PHP recursive function not setting nested arrays

I have a variable set coming in from a form, and due to poor design by the original developer, the form will submit empty form element values as '' (empty single quotes), this wreaks havoc with some of the queries I am having to write because the functions read those as being values. I wrote a function to set any instances of '' to false, mainly because just capturing for if the value is false wasn't working. I re-wrote the function to be recursive in order to drill down into nested arrays.

function validateVars($vars){
    foreach($vars as $k => $v){
        is_array($k) ? validateVars($k) : $vars[$k] = ($v == '' ? FALSE : $v);
    }
    return $vars;
}

problem is, it sets all of the indexes with '' as the value to false as it should, but it isn't actually going into the arrays to set their values. Here's a sample dump:

array(14) { 
    ["title"]=> string(3) "JLR" 
    ["issue"]=> array(3) { 
        ["jobs"]=> string(11) "66055,66056" 
        ["Ids"]=> string(0) "" 
        ["DateRange"]=> string(0) "" } 
    ["article"]=> array(2) { 
        ["Jobs"]=> string(0) "" 
        ["Ids"]=> string(0) "" } 
    ["issueDateFields"]=> string(11) "DateCreated" 
    ["articleDateRange"]=> bool(false) 
    ["articleDateFields"]=> string(11) "DateCreated" 
    ["AdsJobs"]=> bool(false) 
    ["FMBMJobs"]=> bool(false) 
    ["AdsIds"]=> bool(false) 
    ["FMBMIds"]=> bool(false) 
    ["adsDateRange"]=> bool(false) 
    ["adsDateFields"]=> string(11) "DateCreated" 
    ["fmbmDateRange"]=> bool(false) 
    ["fmbmssueDateFields"]=> string(11) "DateCreated" 
}

Upvotes: 0

Views: 77

Answers (2)

Joao
Joao

Reputation: 2746

It seems like you're passing the array key into is_array() which will always evaluate to false.

Also, you're changing the local $vars variable but not using the output:

$vars = [];//this is your array

$vars = validateVars($vars);

function validateVars($myVars){
    foreach($myVars as $k => $v){
        is_array($v) ? $myVars[$k] = validateVars($v) : $myVars[$k] = ($v == '' ? FALSE : $v);
    }
    return $myVars;
}

Which would modify your initial array.

Upvotes: 0

deceze
deceze

Reputation: 522075

  1. You're testing the key and not the nested array value, and
  2. you're doing nothing with the return value.

It needs to be this:

function validateVars(array $vars){
    foreach ($vars as &$value) {
        if (is_array($value)) {
             $value = validateVars($value);
        } else if ($value == '') {
             $value = false;
        }
    }
    return $vars;
}

If you like one-liners, at least do it properly. ;)

function validateVars(array $vars) {
    return array_map(
        function ($v) {
            return is_array($v) ? validateVars($v) : ($v == '' ? false : $v);
        },
        $vars
    );
}

Upvotes: 2

Related Questions