-3

I am trying to extract part of a number using sustr() but the following is not working:

$num = 012014;

echo substr($num, 0,2);

returns 51

BUT

$num = '012014';

echo substr($num, 0,2);

returns 01

I want it to return 01 can someone help me

thpl
  • 5,810
  • 3
  • 29
  • 43

4 Answers4

0

Is is not a normal number, when it's prepended with a zero (0). Then it's an octal number

If you treat $num as a string, it'll work.

$num = '012014';
echo substr($num, 0,2);
Trolley
  • 2,328
  • 2
  • 23
  • 28
0

I guess you must declare the variable as string like this.

$num = '012014'; 
echo substr( (string)$num, 0, 2 );
Tiny
  • 27,221
  • 105
  • 339
  • 599
PaulusCh
  • 71
  • 1
  • 3
-1

Ooops I didn't notice the leading zero. You should just define $num as a string

$num = '0123';
Samuil Banti
  • 1,735
  • 1
  • 15
  • 26
-1

Please try this

$num = 123424;
$num = (string)$num;

echo substr($num, 0,2);
ahmad05
  • 438
  • 2
  • 6
  • 23
  • This wont work with the original number: http://codepad.org/z2qAPMZb – Jim Jun 30 '14 at 08:40
  • i have tested code on this " http://writecodeonline.com/php/" and it works – ahmad05 Jun 30 '14 at 10:48
  • Have you tested using `$num = 012014;`? Your code will not work for numbers beginning with a `0` because PHP will treat them as an octal number. – Jim Jun 30 '14 at 11:49