1

I have realized that PHP can treat string variables as numbers (as long as int or float values are stored in the string variables), for example:

<?php
    // Declaring two int numbers and one float number as string variables
    $i = "10";
    $j = "3";
    $f = "5.2";
    
    // Adding an int number and a float number represented as string variables
    $result = $i + $f;
    echo $result . "<br />"; // will print "15.2"
    
    // Comparing two int numbers represented as string variables
    if ($i > $j)
    {
        echo "i is bigger than j"; // this statement will be executed
    }
    else
    {
        echo "i is not bigger than j";
    }
?>

My question is, why do we have int and float data types in PHP, why not just store int and float numbers in string variables like I did in the above code?

8
  • int and float data types are used in those operations, PHP simply provides 'silent' type coercion to convert the strings into int or float before performing the numeric operations. Those types need to exist in the language otherwise type coercion would not be possible, and those numeric operations would not exist either. Mar 18, 2023 at 21:23
  • @Ben Cottrell But why can we explicitly create int or float variables (for example: $i = 10; $f = 2.4;)? I mean in the Bash shell for example, I think an int variable is stored as a string, but you can't explicitly create an int variable I think. Mar 18, 2023 at 21:40
  • @Ben It could directly work on strings. Might be a bit inefficient, but does it matter? Mar 18, 2023 at 21:40
  • @user Type is strictly only the property of an object, not a variable in that language. Mar 18, 2023 at 21:42
  • 2
    Bash only has strings, and it's a total nightmare. In principle, it's possible, but in practice, programming languages usually expose data types that map well onto the hardware. Storing numbers 1-digit-per-char is outstandingly inefficient, and you can't do arithmetic on number strings until you convert them to better representations first, anyway.
    – Alexander
    Mar 18, 2023 at 21:59

1 Answer 1

3

Efficiency. All computers can do integer math extremely efficiently, as in billions of operations per second, and most (these days) can do the same with floating point.

String math? Not so much.

PHP is fairly fast, but I'm sure many would wish it faster. Do we really want to slow it down more, for some definition of elegance? To what real purpose?

Analogous questions might be: why do we need a 64-bit computer? A 1-bit computer can do all the same things. Or: why do we need the x86 architecture when a Turing machine has been proven to be able to do all the same things?

Not the answer you're looking for? Browse other questions tagged or ask your own question.