• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

My Monkey Do

A Log of Coding Solutions

  • Home
  • Web Hosts
  • Tools
  • About

PHP – ‘anything’ in_array 0 is true

June 27, 2019 by Webhead

$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;

Filed Under: Coding Tagged With: php

Primary Sidebar

Topics

apache apple block editor chrome cms css debug eCommerce embed firebug firefox git gmail goDaddy google hosting htaccess html html 5 IE crap image iPad iPhone javascript jquery linux localization mac os x ms sql mysql open source optimize php php 5.3 responsive rest api seo svg tinymce woocommerce wordpress wpengine xss yii youtube




Categories

  • Coding
  • Off the Shelf
  • Plugins
  • Random Thoughts
  • Server Stuff
  • Tools