2

Following is an associative array I am using in a chunk of PHP code that creates an organized table of performance dates and information using data from a SQL database. The code appears to have no problems (to me), but is not behaving correctly when the webpage loads (certain dates are not appearing).

$months = array(
    01 => 'January',
    02 => 'February',
    03 => 'March',
    04 => 'April',
    05 => 'May',
    06 => 'June',
    07 => 'July',
    08 => 'August',
    09 => 'September',
    10 => 'October',
    11 => 'November',
    12 => 'December',
);

When I run a 'var_dump', the output is as follows:

array(11) {
    [1]=> string(7) "January" 
    [2]=> string(8) "February" 
    [3]=> string(5) "March" 
    [4]=> string(5) "April" 
    [5]=> string(3) "May" 
    [6]=> string(4) "June" 
    [7]=> string(4) "July" 
    [0]=> string(9) "September" 
    [10]=> string(7) "October" 
    [11]=> string(8) "November" 
    [12]=> string(8) "December" }

The whole line for 'August' is missing, and the key for 'September' is now [0].

Can anybody explain where the error is in my code?

Disclaimer: I have solved the issue by removing the leading zeroes from the first nine keys, but I am confused as to why it mattered?? Thanks in advance for any explanation.

5
  • @Nick great find. That is an exact duplicate. Commented May 12, 2018 at 4:00
  • 1
    @mickmackusa I just kept following the "this is a duplicate of..." links! :) Commented May 12, 2018 at 4:01
  • Ah right. Then, happy to get the assist. Commented May 12, 2018 at 4:02
  • @mickmackusa Thank you for your editing and pointing to the answer. As an amateur coder I have not worked with octal numbers, only decimal, hexadecimal, and binary; I was not aware of the leading zeroes causing it to be interpreted as an octal! Commented May 13, 2018 at 2:47
  • Of course. This is a sneaky occurrence to debug for anyone not familiar with rarely used octals. Happy coding. Commented May 13, 2018 at 2:55

1 Answer 1

2

08 and 09 are invalid octal literals... So what you need to do is either of:

  1. Name your keys as proper integers (without 0 prefix)
  2. Or, use your keys as strings, like you mentioned "associative array" in question, your array should be like this:
<?php
$months = array(
    "01" => 'January',
    "02" => 'February',
    "03" => 'March',
    "04" => 'April',
    "05" => 'May',
    "06" => 'June',
    "07" => 'July',
    "08" => 'August',
    "09" => 'September',
    "10" => 'October',
    "11" => 'November',
    "12" => 'December',
);

sorry wanted to comment but couldn't, new user here

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

1 Comment

This is an answer (correct as it happens) to the question. It shouldn't have been a comment so no need to apologise.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.