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 28 Previous

Item 547239

What does the following code output:

$s = str_split("abcdefghijklmnopqrstuvwxyz", 2);
echo ($s[3][0]="e") ? $s[3][0].$s[2][0] : $s[1][0].$s[0][0];

A: "ca"
B: "ge"
C: "ga"
D: "ee"
E: Notice: Cannot use object of type string as array in test.php on line 3 F: Fatal error: Call to undefined function str_split() in test.php on line 2


There's a str_split function and it splits a string using a given chunk size and returns the result as an array of strings, so that is not the problem.

You also can access the individual characters of a string using array indices so line 3 correct as far as syntax goes.

I hope you've noticed the bug on line 3. It's a very common mistake and very easy to overlook. In line 3 no comparison operator (==, ===, etc.) was used but an assignment operator. Therefore the expression $s[3][0]="e" assigns "e" to $s[3][0] and because "e" will evaluate to 'not false' the first part right after the question mark will be echoed to the browser. And because the original value "g" of $s[3][0] was overwritten by "e", "ee" will show up in your browser.

Here's a good lesson for you that can save you (and those who maintain your code) some headaches: In this situation where you compare a variable with some constant value swap the operands:

echo ("e"=$s[3][0]) ? ....

It looks weird but now you'll get an error and your typo will not cause a bug.