0

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);
1
  • 3
    $url[$key] = "{$key}={$val}"; perhaps? If I understood your question correctly. Commented Nov 16, 2016 at 16:02

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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"
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.