0
$colors = array();

for($i = 1; $i <=2; $i++) {
    if ($i == 1) {
        $current_colors = array('color1' => 'blue', 'color2' => 'red');
    }    
    else {
        $current_colors = array('color3' => 'yellow', 'color4' => 'green');
    }
    array_push($colors, $current_colors);
}

var_dump($colors);

This script returns:

array(2) {
  [0]=>
  array(2) {
    ["color1"]=>
    string(4) "blue"
    ["color2"]=>
    string(3) "red"
  }
  [1]=>
  array(2) {
    ["color3"]=>
    string(6) "yellow"
    ["color4"]=>
    string(5) "green"
  }
}

The array that I need shouldn't have any index (in this case 0 and 1).

Instead of array_push() I also tried it with array_merge() but it returns an empty array.

How can I remove the index?

Reza Saadati
  • 1,224
  • 13
  • 27
  • So what should your array look like? Are you wanting all four of the colours merged as one array? So that `$colours` has `color1`, `colour2` etc directly under it (without the `[0]` and `[1]`)? – Obsidian Age Aug 27 '18 at 02:35
  • @ObsidianAge yes, exactly! – Reza Saadati Aug 27 '18 at 02:35
  • You can't use `array_push` for this, as that will always create a numeric index. You'll want to access the array itself with square bracket notation. – Obsidian Age Aug 27 '18 at 02:37
  • Possible duplicate of [How to push both value and key into array](https://stackoverflow.com/questions/2121548/how-to-push-both-value-and-key-into-array) – Obsidian Age Aug 27 '18 at 02:37

2 Answers2

2

You need to do this:

$colors = array_merge($colors, $current_colors);

array_merge() won't update $colors. You need to update it by yourself

chingcm
  • 121
  • 5
0

Arrays in PHP always have keys; albeit numeric ones if you don't specify them yourself. If you need to access the array as if it has no keys then you can use array_values().

Chris Cousins
  • 1,862
  • 8
  • 15