Vladimir
Vladimir

Reputation: 836

Bizarre PHP output

Can someone explain to me why this code

$ar = [
  'item' => '−2',
];

for ($i = 1; $i >= -2; $i--) {
  foreach ($ar as $x => $y) {
    if ($y == $i) {
      echo $y . ' == ' . $i . "\n";
    }
  }
}

Produces

−2 == 0

Upvotes: 1

Views: 85

Answers (3)

cHao
cHao

Reputation: 86505

The "−" in your array value is actually Unicode Character 'MINUS SIGN' (U+2212), which PHP doesn't consider as belonging in a numeric string. (It only recognizes U+002D, the HYPHEN-MINUS, partly because it doesn't support UTF-8 at that level; to a stock PHP, all strings are byte strings.) Since it's not numeric, and the string doesn't even start with numeric data, its numeric value is 0.

If you delete the Unicode dash and type in a dash instead (which should enter the ASCII one), the script should work as expected.

Upvotes: 3

S.Thiongane
S.Thiongane

Reputation: 6905

After some researches, i understand know how it works. First, read this from the doc:

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).

So '-2' is considered as 0 because of - (initial portion), so the if statement will be entered only when i == 0 meaning -2 == 0. And then echo $y - $i.

Upvotes: 0

George Brighton
George Brighton

Reputation: 5151

You're getting that result because -2 is a string - PHP is not performing a numerical comparison. Change == to === to use strict comparison, which will only return true if the values and their types are equivalent.

Upvotes: 4

Related Questions