0

I want to create an array in a for-loop so i can adjust the size ($i) of the array. I've tried this:

$array = array();
for($i = 1; $i <= 5; $i++) {
    array_push($array,
        $i => array(
            "id" => "",
            "option" => ""
        ) 
    );
}

But I get the following error:

Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW) in ...

I'v also tried to make it a string by doing $i."" on line 4 but that doesn't seem to work either. Does anyone know why?

0

3 Answers 3

3

More idiomatic would be:

$array = array();
for($i = 1; $i <= 5; $i++) {
    $array[$i] = array(
                "id" => "",
                "option" => "") ;
}

However note that this will give you array indexes from 1-5. Arrays are usually indexed from 0:

$array = array();
for($i = 0; $i < 5; $i++) {
    $array[$i] = array(
                "id" => "",
                "option" => "") ;
}

But this can be done without specifying the key:

$array = array();
for($i = 1; $i <= 5; $i++) {
    $array[] = array(
                "id" => "",
                "option" => "") ;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I would do it this way without specifying the key. Far easier unless you require the key.
3

try this:

$array = array();
for($i = 1; $i <= 5; $i++) {
    $array[$i] = array(
            "id" => "",
            "option" => ""
        );
}

Comments

1

Remove the $i =>

$array = array();
for($i = 1; $i <= 5; $i++) {
    array_push($array, array(
            "id" => "",
            "option" => ""
        ) 
    );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.