user1214678
user1214678

Reputation:

Increment php array with key value pairs in a loop

How do I increment(add more values) to an array with key value pairs in a loop.

$field['choices'] = array(
   'custom' => 'My Custom Choice'
 );

Let's says I want to add three more choices from another array?

Output I want to achieve:

$field['choices'] = array(
  'custom1' => 'My Custom Choice1'
  'custom2' => 'My Custom Choice2'
  'custom3' => 'My Custom Choice3'
  'custom4' => 'My Custom Choice4'
);

Upvotes: 1

Views: 11214

Answers (5)

Mic1780
Mic1780

Reputation: 1794

Here is the code i would use to add $otherArray values to a custom increment array key value

if (count($field['choices']) === 1) {
    $field['choices']['custom1'] = $field['choices']['custom'];
    unset($field['choices']['custom'];
    $i = 2;
} else {
    $i = count($field['choices']) + 1;
}//END IF
foreach ($otherArray as $key => $val) {
    $field['choices']['custom' . $i] =  $val;//Where val is the value from the other array
    $i++;
}//END FOREACH LOOP

Upvotes: 0

hakre
hakre

Reputation: 197659

As you had outlined in your question:

$field['choices'] = array(
   'custom' => 'My Custom Choice'
 );

So:

$array = $field['choices'];

to simplify the following example:

$otherArray = range(1, 3); // another array with 3 values

$array += $otherArray; // adding those three values (with _different_ keys)

done. The + operator with arrays is called union. You find it documented here:

So as long as the other array you want to add has three different keys compared to the one array you add it to, you can use the + operator.

Upvotes: 0

Barmar
Barmar

Reputation: 780818

Iterate, and concatenate the index to the prefix in your key:

for ($i = 2; $i <= 4; $i++) {
    $field['choices']['custom' . $i] = 'My Custom Choice' . $i;
}

Upvotes: 1

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174957

You would want to use array_merge().

From the manual:

array array_merge ( array $array1 [, array $... ] )

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

Upvotes: 0

Matthew R.
Matthew R.

Reputation: 4350

You can use the array functions to sort or merge.

Or you can do something like this:

$field['choices']['custom'] = 'My Custom Choice';
$field['choices']['custom2'] = 'My Custom Choice';
$field['choices']['custom3'] = 'My Custom Choice';
$field['choices']['custom4'] = 'My Custom Choice';

Upvotes: 0

Related Questions