Check out Scrivo

Do you want to try out Scrivo? Then here's a demo for you that does not just get your feet wet but lets you plunge right in.

Contact us

For more information, please contact us. We're happy to help you out!

Next Sep 7 Previous

Item 547184

You are building a web-shop plugin to help people finding their perfect guitar. For the guitar brands selection procedure you copy and paste the following code from an online forum:


$brands[$key] = "Fender"; $brands[] = "Gibson"; $brands["key"] = "Ibanez"; $brands[36] = "G&L";

print("The best brand is {$brands[key]}"); ?>

[/code]

Which guitar manufacturer is going to be very happy?

A: Fender
B: Gibson
C: Ibanez
D: G&L
E: Fatal Error

Answer

I'm trying to trick you in selecting answer D. The value of $brands[36] that is set in line 5 to "Fender" is overwritten in line 8 by "G&L". However in line 10 the value of $brands[[/c]key] was printed out and not the value of $brands[[/c]$key].

This will cause PHP to interpret key as an undefined constant and this evaluates to the string "key". Therefore answer C is correct and Ibanez is the lucky company.

Although "Fatal Error" is a rather cool name for a guitar brand this code runs fine and does not end in a fatal error but it does raise a notice.

Note that this is actually a common programming mistake: undefined constants are assumed to be strings. In this case the code is not doing what it appears to do and when notices are not displayed it will not be signaled.

Also note that the array key for the "Gibson" brand is not but 37. That's because an integer index was used in line 5 and PHP uses the largest integer array index to determine the next one.