Adding null values to an array

14,855

Solution 1

Oh my... It was just a simple typo:

...
} elseif($Parameter->isDefaultValueAvailable()) {
    $paramaters[$Parameter->name] = $Parameter->getDefaultValue();
} else {
...

Shame on me!

Solution 2

How about pre-initializing $parameters before entering the foreach loop:

$parameters = array(
    $searchKey => null,
    $summary => null,
    $title => null,
    $authors => null,
    $paginationPage => 0
);
Share:
14,855
Rene Terstegen
Author by

Rene Terstegen

Updated on June 15, 2022

Comments

  • Rene Terstegen
    Rene Terstegen over 1 year

    I have the this method:

    public function search($searchKey=null, $summary=null, $title=null, $authors=null, $paginationPage=0) { 
        ... 
    }
    

    And I'm trying to retrieve all parameters with this:

    $Class = new Search();
    
    // Get parameters
    $ReflectionMethod = new \ReflectionMethod($Class, "search");
    try {
        foreach($ReflectionMethod->getParameters() AS $Parameter) {
            if(array_key_exists($Parameter->name, $this->params)) {
                $parameters[$Parameter->name] = $this->params[$Parameter->name];
        } elseif($Parameter->isDefaultValueAvailable()) {
            $paramaters[$Parameter->name] = $Parameter->getDefaultValue();
        } else {
                ...
        }
    } catch(\Exception $e) {
            ...
    }
        // Call function
    return call_user_func_array(array($Class, "search"), $parameters);
    

    My $this->params has this content:

    array
      'paginationPage' => int 2
      'id' => int 30
      'searchKey' => string 'test' (length=4)
    

    Because $summary, $title and $authors are not present, they will get their default value which is null. When assigning a null value to an argument, it will be skipped which results in a $parameters array that looks like this:

    array
      'searchKey' => string 'test' (length=4)
      'paginationPage' => int 2
    

    Which result in a method call like:

    public function search('test', 2, null, null, 0) { 
            ... 
    }
    

    While it should be:

    public function search('test', null, null, null, 2) { 
            ... 
    }
    

    Hopefully you see the problem. How can I make sure those null values are also put into my $parameters array. Adding an invalid value is not possible, because it is user input, so that can be basically everything.

    Edit

    In the example above the method search is hardcoded. But one of the simplified things is that search is actually a variable and because of that search can be anything. This means that I don't know what the parameters of the method are and I can't predefine them before the foreach loop. The solution of predefining the parameters is actually exactly what this code should be doing.