• 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

502 apache apple bluehost bootstrap buddypress chrome cloudways cms css debug drupal eCommerce firebug firefox git goDaddy google google analytics google maps hacked hosting htaccess html html 5 icons IE crap image iPad iPhone javascript jquery linux localization mac os x ms sql mysql open source optimize php tinymce wordpress wpengine yii youtube




Categories

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