Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in_array does not work correctly when dealing with strings [duplicate]

Tags:

php

This code:

var_dump(in_array("000", array(",00", ".00")));
var_dump(in_array("111", array(",11", ".11")));

output:

bool(true)
bool(false)

Why does the first line return true ?

like image 895
Dmitry Drozd Avatar asked Feb 10 '15 17:02

Dmitry Drozd


1 Answers

It has to do with PHP's type coercion. The "000" essentially gets converted to just 0. To force it to use strict type checking, in_array() accepts a third parameter.

var_dump(in_array("000", array(",00", ".00"), true));

output:

bool(false)

EDIT: @andrekeller also pointed out the ".00" probably gets converted to int 0 as well. Moral of the story, don't trust PHP to get types right.

like image 78
Cfreak Avatar answered Oct 21 '22 07:10

Cfreak