How to set 'default' keys and values for array passed as parameter in PHP?

Asked

Viewed 71 times

3

I did a function that takes several arguments, and I decided to pass them by a array to be executed. Ex:

public function funcTeste(array $dados){
    return \count($dados);
}

But this array must have a default number of keys (as if I said $dados = ['key1', 'key2', 'key3'], or something like).

More than that, if this array has parameters not passed (as if the user passes as parameter ['key1' => 'cavalo', 'key2' => 'avestruz']) there is a way in the function to fill this value with a default?

I am using PHP 7.1.23

  • If you need it to be a set value with default values, why did you use the array and did not define the arguments separately?

  • I thought it would be easier to pass the parameters, especially in functions with n required parameters, where, if changing the order of two of them, breaks the entire calculation

  • I’m not sure if there’s what I’m looking for, but if there is, it’ll be a hand on the wheel

  • 2

    You will have to make the conditions within the function to ensure what you need.

1 answer

3


Use array_fill_key() to generate an array with all the required keys and only one value for all. Finally call array_merge() which will merge the default array and the user passed array and the rightmost array (last) will override the values with equal keys.

$padrao =  array_fill_keys(['k1', 'k2', 'k3'], 'valor padrão');
$arr = ['k1' => 'v1', 'k3' => 'v3'];

$novo = array_merge($padrao, $arr);

Exit:

Array
(
    [k1] => v1
    [k2] => valor padrão
    [k3] => v3
)
  • It worked, I combined the array_merge with an array I have now created in the constructor to define the various different values for the array.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.