-2

I got two digital numbers as a string:

The first one looks like this:

$num1 = "00:10:00"

and the second one like this:

$num2 = "00:02:02"

How can I check wether one of them is greater.

utdev
  • 3,942
  • 8
  • 40
  • 70
  • 1
    Separate them into their numeric components and compare those components? Though shouldn't the string sort correctly already? – David Jun 30 '16 at 14:53
  • Is this a time comparison? What is the purpose of the "digital number"? If its time you are looking for consider [this](http://stackoverflow.com/questions/6158726/php-compare-time) – Allen Butler Jun 30 '16 at 15:35

3 Answers3

1

The first one looks like this:

$num1 = "00:10:00"

and the second one like this:

$num2 = "00:02:02"

How can I check wether one of them is bigger.

You need to define what you mean by "bigger". But your numerical values appear to be reading in size from left to right, large to small, which is how numeric values are handled by default.

So what you do, is process the string to turn it into a number, running on the assumption that 01:00:00 is bigger than 00:59:00. All you need to do is remove the non-numeric characters and allow PHP to naturally type cast to integer, or optionally force cast it yourself (as I have here just for clarity):

$number1 = preg_replace("/[^\d]/","",$num1); //remove non-numeric
$number1 = (int)$number1; //cast to integer. This is optional. Just for clarity here. 

$number2 = preg_replace("/[^\d]/","",$num1);
$number2 = (int)$number2;

Giving:

$number1 = 1000
$number2 = 202

Therefore:

if($number1 > $number2){
    //This comparison will return TRUE;
 }
Community
  • 1
  • 1
Martin
  • 22,212
  • 11
  • 70
  • 132
-1

Since $num1 and $num2 are string and not an integer you can't compare with '<' or '>'. You need to explode those variables:

$num1 = explode(':',$num1);

After you explode it, $num1 become an array:

// $num1[0] = 0
// $num1[1] = 10
// $num1[2] = 0

So after you explode $num1 and $num2 you can compare $num1[0] with $num2[0].

For more info about explode:

http://php.net/manual/en/function.explode.php

M1L0
  • 71
  • 9
-2

Use the following code :

<?php
$num1 = "00:13:00";
$num2 = "00:12:02";

$val1 = explode(':', $num1);
$val2 = explode(':', $num2);

if((int)$val1[0] > (int)$val2[0]){
    echo "$num1 is greater than $num2";
}
    else if((int)$val1[1] > (int)$val2[1]){
        echo "$num1 is greater than $num2";
    }
        else if((int)$val1[2] > (int)$val2[2]){
            echo "$num1 is greater than $num2";
        }
            else{ echo "$num2 is greater than $num1";}
?>