PHP - Gotcha

Boolean || returns 0 or 1

If you come from a Perl background, you expect

$error_email = $yaml->get('ERROR_EMAIL') || '';

$error_email to contain the value of $yaml->get('ERROR_EMAIL') if that value is set, or otherwise it should be 'moc.sortnauq|naodk#moc.sortnauq|naodk'. This is not the case with PHP. In PHP, the above code always return 1

count(false) returns 1

If you have a function which query the database, and return the result set as an array, and you want to know how many rows were return, your code may be:

$results = some_function();
$num_row_found = count($results);

But if the query did not returns any rows, some_function() may return false (or some_function() may return false to indicate an error condition (rather than throwing an exception), but we did not check). Now $num_row_found is 1.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License