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

Question:

I made a function that takes several arguments, and decided to pass them through an array to be executed. Ex:

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

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

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

I'm using PHP 7.1.23

Answer:

Use array_fill_key() to generate an array with all required keys and only one value for all. At the end, call array_merge() which will merge the default array and the one passed by the user and the rightmost (last) array will overwrite 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
)
Scroll to Top