I'm trying to write a function that assigns the same key => value pair to multiple array
s. But the assignment doesn't occur.
<?php
// for debugging
error_reporting(E_ALL);
// arrays is an array of reference arrays
function assignKeyValueToArrays($arrays, $key, $value) {
if(!is_scalar($key) || !is_array($arrays)) {
return false;
}
foreach($arrays as $array) {
if(!is_array($array)) return false;
echo "setting $key to $value";
$array[$key] = $value;
}
}
$s = array();
$t = array();
assignKeyValueToArrays(array(&$s, &$t), "a", "blahblah");
// should print array(1) {"a" => "blahblah"} but both print array(0) {}
var_dump($s);
var_dump($t);
?>
The context for this is that I have a script which is doing database queries and assigns keys to both a temporary $queryParams
array and also a $jsonResponse
array. I could just do two assignments but I wanted a more general solution that could handle more arrays.