{"id":1407,"date":"2019-06-27T09:26:42","date_gmt":"2019-06-27T19:26:42","guid":{"rendered":"https:\/\/mymonkeydo.com\/?p=1407"},"modified":"2019-06-27T09:26:42","modified_gmt":"2019-06-27T19:26:42","slug":"php-anything-in_array-0-is-true","status":"publish","type":"post","link":"https:\/\/mymonkeydo.com\/php-anything-in_array-0-is-true\/","title":{"rendered":"PHP – ‘anything’ in_array 0 is true"},"content":{"rendered":"\n
$orderby = 'something';\n$column_names = array( 0, 1, 2, 3, 'acolumn' );\nif ( in_array( $orderby, $column_names ) ) {\n $orderby = 'got here';\n}\nelse {\n $orderby = '';\n}\n\n\/\/ shows 'got here'\necho $orderby;<\/code><\/pre>\n\n\n\nTo 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.<\/p>\n\n\n\n
The same case is true for the opposite case, which is asked and answered on stack overflow<\/a> (you’ll find a more detailed explanation there).<\/p>\n\n\n\n$orderby = 0;\n$column_names = array( 1, 2, 3, 'acolumn' );\nif ( in_array( $orderby, $column_names ) ) {\n $orderby = 'got here';\n}\nelse {\n $orderby = '';\n}\n\n\/\/ shows 'got here'\necho $orderby;<\/code><\/pre>\n\n\n\n