Hi there,

please help somebody out, who is used to typed variables: I have a variable $number = 123; I wanna determine (efficiently!) how many digits the number has. I thought I just use the sizeof() function, that works fine with strings and arrays, but it always gives me 1 as a result, when I call it on $number, even when I do "sizeof($number."test");".

Thanks & happy holidays,
Max

    [man]sizeof/man (which is an alias of [man]count/man), returns the number of elements in an array or properties in an object. For string length, you want to use [man]strlen/man. So you could use it with a number as:

    $digits = strlen(strval($number));
    

    (The strval() probably is not strictly necessary, as PHP is not strongly typed and will dynamically convert variable types as needed; but it does make it clearer what the code is doing and avoids any ambiguity.)

      The strval() probably is not strictly necessary, as PHP is not strongly typed and will dynamically convert variable types as needed; but it does make it clearer what the code is doing and avoids any ambiguity.

      Personally, I think it is clear enough without strval(). For example, we could also write:

      $digits = strlen("$number");

      The above also avoids any ambiguity and is likely to be faster than strval(), yet many people I have seen here would just remove the double quotes.

        Write a Reply...