Question

I have the following code:

 $a = array();
 $b = array('a', 'b');
 for($i=0; $i<3; $i++){
     $a[] = array($b[$i] => array(1, 2, 3));
 }

 print_r($a);

I get the following result:

Array
(
[0] => Array
    (
        [a] => Array
            (
                [0] => 1
                [1] => 2
                [2] => 3
            )

    )

[1] => Array
    (
        [b] => Array
            (
                [0] => 1
                [1] => 2
                [1] => 3
            )

    )
 )

This is what I'm trying to accomplish:

 array (
    'a' => array ( 1, 2, 3 )
    'b' => array ( 1, 2, 3 )
 )

What am I doing wrong? I don't want $a to add numeric elements, but rather contain a, b, c as the indexes. Any suggestions? Thanks

Was it helpful?

Solution 3

You can set the key for $a like so:

$a = array();
 $b = array('a', 'b');
 for($i=0; $i<count($b); $i++){
     $a[$b[$i]] =  array(1, 2, 3);
 }

 print_r($a);

Also, i changed your for loop to use count($b) as you where iterating 1 to many times with your hard coded 3

OTHER TIPS

change the forloop to like this

for($i=0; $i<count($b); $i++){
    $a[$b[$i]] =array(1, 2, 3);
}

You can do,

 $a = array();
 $b = array('a', 'b');
 for($i=0; $i<3; $i++){
     if(isset($b[$i])){
         $a += array($b[$i] => array(1, 2, 3));
     }
 }

DEMO.

Try:

$a[$b[$i]] = array(1,2,3);

One more iteration..

$a = array();
 $b = array('a', 'b');
 for($i=0; $i<3; $i++){
     $a[$b[$i]] = array(1, 2, 3);
 }

 print_r($a);

Let's check what you were doing wrong.

$a = array();
$b = array('a', 'b');  // Count of elements is 2
for($i=0; $i<3; $i++){ // this will loop 3 times assigning 0,1,2 to $i where. You only needed 0 and 1 for an array with 2  elements
    $a[] = array($b[$i] => array(1, 2, 3)); // here you are adding a new element to $a without providing key. So it becomes a numeric indexed array.
}

Solution:

for($i=0; $i<count($b); $i++){ // you could use $i<2 as well however count($b) makes your code more dynamic and result won't be affected if no of elements in $b changes.
    $a[$b[$i]] =array(1, 2, 3); // you put $b[$i] as key for $a which creates an associative array
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top