Categories
PHP

5 PHP Interview Questions Series – 2

Question 1: Explain the output of the below code:

<?php
    $x = true and false;
    var_dump($x);
?>

Surprisingly to many, the above code will output bool(true) seeming to imply that the and operator is behaving instead as an or.

The issue here is that the =  operator takes precedence over the and  operator in order of operations, so the statement $x = true and false  ends up being functionally equivalent to:

<?php
    $x = true;       // sets $x equal to true
    true and false;  // results in false, but has no affect on anything
?>

This is, incidentally, a great example of why using parentheses to clearly specify your intent is generally a good practice, in any language. For example, if the above statement $x = true and false  were replaced with $x = (true and false) , then $x  would be set to false as expected.

Question 2: What will $x  be equal to after the statement $x = 3 + “15%” + “$25” ?

The correct answer is 18.

Share with:

Categories
PHP

5 PHP Interview Questions Series

Question 1: What will be the output of the code below?

<?php
    $str1 = 'bangladesh';
    $str2 = 'bangla';
    if (strpos($str1,$str2)) {
        echo "\"" . $str1 . "\" contains \"" . $str2 . "\"";
    } else {
        echo "\"" . $str1 . "\" does not contain \"" . $str2 . "\"";
    }
?>

The output is: bangladesh does not contain bangla

So what is the explanation?

The problem here is that strpos()  returns the starting position index of $str1 in $str2 (if found), otherwise it returns false. So in this example, strpos()  returns 0 (which is then coerced to false when referenced in the if statement).

Share with: