0

I am trying a add data to an array using a while loop but it seems to be adding the data as a string not array. Loops/arrays are something I'm still learning any help would be great.

$c = 0;
$numberofcustom = 5;
$defaults = array(
'title' => __('Follow Us!', 'smw'),
 'text' => ''
);
while ($c < $numberofcustom) {
    $customnumber = $c + 1;
    $defaults.=array(
        'custom' . $customnumber . 'name' => __('', 'smw'),
        'custom' . $customnumber . 'icon' => __('', 'smw'),
        'custom' . $customnumber . 'url' => __('', 'smw')
    );
    $c++;
}

print_r($defaults);

The problem seems to be with adding the data from the loop if I do a print_r just on that I just get "array" back.

Any help would be appreciated.

UPDATE

I decided I don't need a multi dimensional array so I used the suggestions below and came up with

while( $c < $numberofcustom){
    $customnumber = $c+1;
        $defaults['custom'.$customnumber.'name'] = __('', 'smw');
        $defaults['custom'.$customnumber.'icon'] = __('', 'smw');
        $defaults['custom'.$customnumber.'url'] = __('', 'smw');
    $c++;       
    }

2 Answers 2

1

Don't do this:

$defaults.=array(

            'custom'.$customnumber.'name' => __('', 'smw'),
            'custom'.$customnumber.'icon' => __('', 'smw'),
            'custom'.$customnumber.'url' => __('', 'smw')
             );

dynamic array keys are almost as bad as variables with a dynamic name. Use another array level instead:

$defaults[$customernumber] = array(
    'customname' => __('', 'smw'),
    'customicon' => __('', 'smw'),
    'customurl'  => __('', 'smw'),
);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I edited my question with the solution I came up with based on your answer as I didn't need a multi-dimensional array.
Eh, nothing really it just makes it harder to get the data back out (it's for a WordPress plugin)
1

You need to use $arrayname[] = $var, that's the PHP syntax for appending new items. See this page.

$defaults[] =array(
            'custom'.$customnumber.'name' => __('', 'smw'),
            'custom'.$customnumber.'icon' => __('', 'smw'),
            'custom'.$customnumber.'url' => __('', 'smw')
             );

1 Comment

Thanks that seemed to work. Is there a way to add to the array without making it multi dimensional. I tried $defaults[]= 'custom....' and that didn't work.

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.