Hi,

I have the following simple test script:

<?php
   $links = array('URL'=>'www.google.com');
   print("$links['URL']"); // compilation error
   print("$links[URL]");
   print($links['URL']);
   print($links[URL]); // execution warning
?>

But two lines are giving me problems. Can any one help to explain?

Thanks.

--Mark

Because they are using incorrect syntax. The correct syntax for retrieving an array value is:

print($links['URL']);

OR if you want to print the array value as part of a string then you can use:

print("This is a test url: {$links['URL']} : end of test");

The braces tell php that the string inside is a variable name, a nice safe way of getting the data

print("{$links['URL']}");

In an array it can't quite work out what to do here because it sees the array name and then doesn't know what to do with the square brackets

print("$links['URL']"); // compilation error

The lack of quotes around the key name help a bit but not as safe as the first example. This works, and is valid (as you've discovered) but I don't think it's best practice.

print("$links[URL]");

The best way to do but sometimes they need to be built into a string and that's why the other methods exist. Note the single quotes around the 'URL', this tells PHP that the name isn't going to be anything fancy, just take the name and work with it.

print($links['URL']);

It's looking for a defined, constant, variable called URL and not finding one. Because URL doesn't have a $ or quotes PHP looks for the special case and fails.

print($links[URL]); // execution warning

Thank you Sarah, for the good exlanation. Now I know array key should be single quoted all the time. If it's inside a double quoted string, put the array reference in {}.

One more question on:

print($links[URL]); // execution warning

Is there any setting to turn off the execution warning? I downloaded a PHP database application. It has a lots of lines like this to get values out of query results.

--Mark

Sarah, thanks again...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.