I have an associative array, however when I add values to it using the below function it seems to overwrite the same keys. Is there a way to have multiple of the same keys with different values? Or is there another form of array that has the same format?
I want to have:
42=>56
42=>86
42=>97
51=>64
51=>52
etc etc
Code:
function array_push_associative(&$arr) {
$args = func_get_args();
foreach ($args as $arg) {
if (is_array($arg)) {
foreach ($arg as $key => $value) {
$arr[$key] = $value;
$ret++;
}
}else{
$arr[$arg] = "";
}
}
return $ret;
}
I found this question while researching the exact opposite intended outcome, I have an array of data that has duplicate keys! Here's how I did it (still trying to figure out where in my process things are messing up).
Yup....that just happened.
PHP 7.1
No, you cannot have multiple of the same key in an associative array.
You could, however, have unique keys each of whose corresponding values are arrays, and those arrays have multiple elements for each key.
So instead of this...
...you have this:
A key is an extension of a variable. If you overwrite the variable ... you overwrite the variable.
No, you cannot have. A workaround I use is to have each key/value pair as a new array with 2 elements:
For example, you can access the second key (=42) using:
and the second value(=86) using:
i had the same need too create an array with the same keys, (just to keep performance by using two loops rather than 4 loops).
by using this : [$increment."-".$domain_id] => $article_id; my list of articles in each domain looks like this after a print_r() :
And then by looping through this table to associate article by domain :
you get this