How does strcmp work in PHP?

3

I would like to know how strcmp works in PHP, since I have a doubt as to the result it throws, I know that when it is compared and they are equal it will result in 0, but in other cases the result varies a bit (1, -1 , 5,45 etc.), which would be some examples in which the results vary with a brief explanation.

<?php

    $variable1 = "walter";
    $variable2 = "Alejandro";

    $resultado = strcmp($variable1, $variable2);
    var_dump($resultado);


?>
    
asked by RivW 09.04.2017 в 23:28
source

1 answer

3

As indicated by PHP documentation :

  

Comparison of secure string at binary level

What does this mean?

The comparison will take into account different elements that can vary from one chain to the other, from a space to a capital .

How can we prove this?

Here's an example:

<?php

$cadena = "hola mundo";

$cadena_A = "hola";
$cadena_B = "hola mundo";
$cadena_C = "hola mundo cruel";

if(strcmp($cadena_A, $cadena) < 0){
        print "$cadena_A es menor que $cadena\n";
}


if(strcmp($cadena_B, $cadena) == 0){
        print "$cadena_A es igual que $cadena\n";
}

if(strcmp($cadena_C, $cadena) > 0){
        print "$cadena_A es mayor que $cadena\n";
}

?>

If we execute the program, the result will be:

hola es menor que hola mundo
hola es igual que hola mundo
hola es mayor que hola mundo

Why did you return that result?

As indicated by PHP documentation :

  

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2   and 0 if they are the same.

What do you mean?

A difference is made between the two chains, indicating a value, which will vary if the one has more or less text than the other string against which it is compared.

    
answered by 09.04.2017 / 23:38
source