How to convert a value (which appears to be octal) to string literal in PHP (5.6)? [closed]

-4

How to convert a value (which appears to be an octal) to string literal in PHP (5.6)? Example:

//considere $mes=08; ou $mes=09;
$mes = 08;

echo $mes; // Retorna 0

$result = (string) $mes;
echo $result; // Retorna 0

$result = sprintf('%o', $mes);
echo $result; // Retorna 0

$result = base_convert($mes, 8, 10);
echo $result; // Retorna 0

The value you'd like to find for $ result is '08' (String).

Example usage 1:

$mes = (string) 08;

....
public function mesPorExtenso($mes) {

    switch ($mes) {
        case '08': //Não entra no case porque $mes é 0
            $mes = "Agosto";
        break;
    }
}
...

Example usage 2:

$mes = 08;

....
public function mesPorExtenso($mes) {
    switch ($mes) {
        case 08: // PHP Parse error: Invalid numeric literal
            $mes = "Agosto";
        break;
    }
}
...

What is the correct way to convert the 08 value to a string '08'?

The mesPorExtension () method is called dozens of times, The value is defined by the caller. I just want to make sure the $mes variable is a string.

    
asked by anonymous 03.07.2018 / 19:05

2 answers

5

The problem is to use 0 when declaring the month. From your web server you will already receive the value in string , so only in cases that you put directly in the code will you have problems.

To work correctly, declare string $mes = '08' or use integer without% $mes = 8 .

Reference in the PHP documentation: Integer

    
03.07.2018 / 21:02
4

When you enter 0 in front of a number, it is considered an octal. The problem is that in the case of the 08 and 09 values, in versions prior to PHP 7 they ignore the rest of the number. As of PHP 7 a conversion error will be thrown.

  

Warning In versions prior to PHP 7, if an invalid digit is passed   for octal integer (for example, 8 or 9), the rest of the number will be   ignored. Since PHP 7, an interpretation error is issued.   Information on link

To work out what you want, you need to pass a String.

    
03.07.2018 / 21:04