MontrealDevOne
MontrealDevOne

Reputation: 1044

Compare two integers

How do you compare two integers in php?

I have tried

print (1 > 2);           // No output
$a = 1;
$b = 2;
$c = ($a > $b) ? true : false;
print ($c);              // No output

var_dump works fine. I have the latest PHP installed.

Upvotes: 5

Views: 19442

Answers (7)

Reena Mori
Reena Mori

Reputation: 645

You can compare two variable(int,float,string) value in php using Spaceship operator (New feature of php 7)

  • Integers
    echo 1 <=> 1; // 0
    echo 1 <=> 2; // -1
    echo 2 <=> 1; // 1
  • Floats
    echo 1.5 <=> 1.5; // 0
    echo 1.5 <=> 2.5; // -1
    echo 2.5 <=> 1.5; // 1
  • Strings
    echo "a" <=> "a"; // 0
    echo "a" <=> "b"; // -1
    echo "b" <=> "a"; // 1

Upvotes: 3

Ahoura Ghotbi
Ahoura Ghotbi

Reputation: 2896

Either use something like:

$c = $a > $b;
echo $c;

or use var_dump()

Upvotes: 0

Etan
Etan

Reputation: 17544

echo ($a > $b) ? "true" : "false";

Upvotes: 0

King Skippus
King Skippus

Reputation: 3826

The comparisons in your example are working fine. The issue is that when you print true or false values, they don't render anything. Try something like this instead:

$ php -a
$ print (1 > 2) ? 'true' : 'false';
$ $a = 1;
$ $b = 2;
$ $c = ($a > $b) ? true : false;
$ print ($c) ? 'true' : 'false';

Upvotes: 0

Ingmar Boddington
Ingmar Boddington

Reputation: 3500

You are trying to print false in both cases which will by casted to an empty string, hence you are not seeing anything printed.

Try using var_dump instead or outputting a string with a proper control structure (i.e. if else)

Upvotes: 3

Rawkode
Rawkode

Reputation: 22562

Both of your comparisons return false which will not print out a value.

<?php
echo true;
echo false;

Upvotes: 5

xdazz
xdazz

Reputation: 160833

print(false) will output nothing.

If you want to display false, try var_export(false)

Upvotes: 3

Related Questions