I'm trying to pass an array that has defined keys into a function parameter, but when I call the function it creates it's own set of numeric keys for the array. How can I make it use the same keys?
<?php
$param = [
"foo" => "bar",
"bar" => "foo",
];
function amazonRequest($AmazonQuery) {
$url = array();
foreach ($AmazonQuery as $key => $val) {
$key = str_replace("%7E", "~", rawurlencode($key));
$val = str_replace("%7E", "~", rawurlencode($val));
$url[] = "{$key}={$val}";
print_r($url);
}
}
amazonRequest($param);
print_r($param);
You are autonumbering an empty array:
$url[] = "{$key}={$val}";
Of course it will be numbered starting from 0. You can use $url[$key] = "{$key}={$val}";
if you want the keys to be the same.
When you add new items to an array using: $array[] = "something"
, it will add an indexed key [0 => 'something', ...]
always starting at 0.
If you want to add a new item with an associative key (non sequenced or string) you need to define the key name:
// Since you get the key in your foreach loop, just add it like this:
$url[$key] = "{$key}={$val}";
The new $url
-array should now look like:
[
"foo" => "foo=bar",
"bar" => "bar=foo"
]