Home > Net >  How do I add something to the array instead of replacing it? PHP
How do I add something to the array instead of replacing it? PHP

Time:02-15

I filling to the array with foreach, I can't figure out how not to replace the value, but assign a new one

$class_groups[one] = array('one');
$class_groups[one] = array('two');
$class_groups[two] = array('three');


var_dump($class_groups)

Output

array(2) { ["one"]=> array(1) { [0]=> string(3) "two" } ["two"]=> array(1) { [0]=> string(5) "three" } }

What I want to get:

array(2) { ["one"]=> array(2) { [0]=> string(3) "one" [1]=> string(3) "two" } ["two"]=> array(1) { [0]=> string(5) "three" } }

CodePudding user response:

Both of these snippets produce your desired output:

$class_groups['one'] = [ array('one'), array('two') ];
$class_groups['two'] = array('three');

OR

$class_groups['one'][] = array('one');
$class_groups['one'][] = array('two');
$class_groups['two'] = array('three');

CodePudding user response:

With line two in your example you are replacing the value assigned in line one. You have two possibilities:

$class_groups['one'][] = 'one';
$class_groups['one'][] = 'two';
$class_groups['two'] = array('three');

Or:

$class_groups['one'] = array('one', 'two');
$class_groups['two'] = array('three');
  •  Tags:  
  • php
  • Related