0

I have a problem concerning array keys. I'm trying to result the following array:

$options = array(
    'number 3' => 'number 3',
    'number 6' => 'number 6',
    'number 9' => 'number 9',
    'number 12' => 'number 12'
);

I'm using the following function:

function number_count() {

    $array = array();

    for( $i = 3 ; $i+3 ; $i <= 12 ) {
        $string_i = print_r($i, true);
        $array[$string_i . 'px'] = $string_i . 'px';
    }

    return $array;
}

    $options= number_count();

I know there is some serious error that I can't understand because the page is blocking when I try to execute the code. How I can insert a variable and key, and variable and value in the array?

0

2 Answers 2

2

There's actually an error in your for-loop...

It should be:

for ($i = 3;$i <= 12; $i = $i + 3) {
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, yeah, I didn't saw that. Thanks!
2

Don't use the results of print_r as an associative index. You can just use $i:

for ($i = 3; $i <= 12; $i + 3) {
    $array[$i . 'px'] = $i . 'px';
}

Also, as pointed out by Marty, the increment code should appear as the third expression in your for loop (you have it as the second, so the loop will run infinitely).

2 Comments

Thanks for the tip. +1 I didn't know that there can be a string and integer in the array key.
PHP will automatically cast the integer to a string when using the concatenation operator.

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.