0

In PHP I had to compare if an integer variable was less than a value of an array, but I had an error in the code and I found by chance an unexpected behavior.

I was comparing the integer with the array itself and it was returning true. Do you know why?

I've been searching about this in StackOverflow and php.net (PHP types comparisons) and I didn't found a specific answer.

Here you have a little code to test this.

<?php

$myArray = array();
$myInt = 1;

if($myInt < $myArray){
    echo "Int less than array\n";
}

if($myInt == $myArray){
    echo "Int equal to array\n";
}

if($myInt > $myArray){
    echo "Int greater than array\n";
}

I've tried different values for $myInt and different contents for $myArray and it always prints this:

Int less than array
6
  • Casting an empty array to int results in 0. Commented Sep 2, 2016 at 8:01
  • @JonStirling That's what I would have thought as well, but then the last condition should match and not the first... Commented Sep 2, 2016 at 8:04
  • 1
    @jeroen Ah. Chuck Norris saves the day again :P Commented Sep 2, 2016 at 8:06
  • @JonStirling Yep :-) Commented Sep 2, 2016 at 8:06
  • 1
    Can I ask why You need to do such comparison? What You want to achieve with this? Commented Sep 2, 2016 at 8:09

1 Answer 1

4

Comparing an array to anything else result in array is always greater :

see php doc - section Comparison with Various Types

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.