1
if ($source=="test") {
header("Location: $testurl['google']"); 
}

This is supposed to redirect to google.com if the url is example.com/redirect.php?source=test but it doesn't work. If I change the array key to 1 and change the location to $testurl[1] it does works. Why does it work with indexed but not associative arrays?

1
  • its typo, use as if ($source=="test") { $url = $testurl['google']; header("Location:$url"); } Commented Jan 7, 2020 at 4:29

1 Answer 1

0

Assuming that you have somewhere an array $testurl which has an element google:

$testurl = [
  'google' => 'https://google.pl'
];

Then you can use it like this:

if ($source=="test") {
    header("Location: $testurl[google]"); 
}

or

if ($source=="test") {
    header("Location: {$testurl['google']}"); 
}

or in my opinion the best option, like this:

if ($source=="test") {
    header('Location: ' . $testurl['google']); 
}

It is simply how it is defined: https://www.php.net/manual/en/language.types.string.php#language.types.string.parsing

There is a sentence:

// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it works! I used the best option.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.