-1

This is as simple as it gets, but I can't see why I'm getting 0 when I echo $num[3] from this PHP array.

$num=[00000004,00000002,00000005,00000009]; echo $num[3];

3
  • 1
    Preceding the number with a 0 (zero) denotes an octal notation.. Commented Feb 11, 2021 at 12:56
  • 2
    This will throw a fatal error if you use PHP 7 or higher. Commented Feb 11, 2021 at 12:57
  • Thank you. I tried other numbers and I'm seeing an octal result. I never knew about that. I'll need to make them a string if I want the leading zeros in there. Commented Feb 11, 2021 at 12:59

4 Answers 4

2

Based on Integers Manual

To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x. To use binary notation precede the number with 0b.

Your values are actually representing octal notation and that's why you are leading to issue.

Convert them to string:

$num=[
    '00000004',
    '00000002',
    '00000005',
    '00000009'
  ]; 
echo $num[3];

Output: https://3v4l.org/ktsJY

Note:- From Php7 onward it will give you Parse error: Invalid numeric literal

https://3v4l.org/W3aD0

Sign up to request clarification or add additional context in comments.

2 Comments

@GertB AlivetoDie's answer mentioning "octal" was the real problem. So this is the best answer. It is acceptable to not use the quotes in php5, but the results were showing octal numbers.
True, it is the most complete answer. Adding the php7 note was a very good idea btw. I just think that its a lot of information for a simple mistake.
2

Because of the leading zero's, it needs to be a string, not a number:

$num=['00000004','00000002','00000005','00000009']; echo $num[3];

Comments

1

The data is not stored correct, they are stored as a number but they are strings so they need to be stored as a string. When I run your code it throws an error

Parse error:  Invalid numeric literal in [...][...] on line 2

The code below wil return 00000009

$num=['00000004','00000002','00000005','00000009']; echo $num[3];

1 Comment

hmmz, looks like my answer... Only php 7+ will throw an error btw
-1

Your syntax is not correct,try this

$num = array("00000004","00000002","00000005","00000009");
echo $num['3'];

3 Comments

Whats wrong with the syntax??? Your answer does exactly the same as my answer..
Thanks for explaining,the values are stored as string therefore you must enclose in quotation marks.
And why would you change the [...] to array(... ), thats not needed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.