PHP – ‘anything’ in_array 0 is true

$orderby = 'something';
$column_names = array( 0, 1, 2, 3, 'acolumn' );
if ( in_array( $orderby, $column_names ) ) {
    $orderby = 'got here';
}
else {
    $orderby = '';
}

// shows 'got here'
echo $orderby;

To my surprise an any array with value of 0 will cause the in_array function to be true. This is because PHP converts the string being compared to a number. ‘something’ == 0 is true because ‘something’ gets converted to 0 as a number.

The same case is true for the opposite case, which is asked and answered on stack overflow (you’ll find a more detailed explanation there).

$orderby = 0;
$column_names = array( 1, 2, 3, 'acolumn' );
if ( in_array( $orderby, $column_names ) ) {
    $orderby = 'got here';
}
else {
    $orderby = '';
}

// shows 'got here'
echo $orderby;

The solution is really to almost always set the third parameter to TRUE. This puts in_array into strict mode which compares the type of the needle.

$orderby = 'something';
$column_names = array( 0, 1, 2, 3, 'acolumn' );
if ( in_array( $orderby, $column_names, true ) ) {
    $orderby = 'will not get here';
}
else {
    $orderby = '';
}

// shows ''
echo $orderby;
Tagged with:

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.