Forum Moderators: coopster

Message Too Old, No Replies

Sending a dynamic list of keys=>vals to a function

         

csdude55

6:04 pm on Oct 1, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have a function that looks like this:

function foo($variable, ...$array) {
foreach ($array as $key)
echo "$key\n";
}

foo('lorem', 'ipsum', 'quia', 'dolor');

// Result:
// ipsum
// quia
// dolor


But now let's say that I want to change it up and make $array an associative array. I know that this would work:

function foo($variable, $array) {
foreach ($array as $key => $val)
echo "$val\n";
}

foo('lorem', ['one' => 'ipsum', 'two' => 'quia', 'three' => 'dolor']);


but is there a way to do it WITHOUT declaring it as an array (eg, wrapping it in [ ]) when I call the function?

Dimitri

10:39 pm on Oct 1, 2022 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member Top Contributors Of The Month



but is there a way to do it WITHOUT declaring it as an array (eg, wrapping it in [ ]) when I call the function?

No.

An associative array, is... an array.

A workaround might be something like that :

function foo($variable,...$array)
{
$n=count($array);
for($i=0;$i<$n;$i+=2)
{
echo "Key: " , $array[$i] , " - " , "Value: " , $array[$i+1] , "\n";
}
}

foo('lorem','one','ipsum', 'two','quia','three','dolor');


ouput:
Key: one - Value: ipsum
Key: two - Value: quia
Key: three - Value: dolor