Adding an item to an associative array

PhpArraysAssociative Array

Php Problem Overview


//go through each question
foreach($file_data as $value) {
   //separate the string by pipes and place in variables
   list($category, $question) = explode('|', $value);

   //place in assoc array
   $data = array($category => $question);
   print_r($data);

}

This is not working as it replaces the value of data. How can I have it add an associative value each loop though? $file_data is an array of data that has a dynamic size.

Php Solutions


Solution 1 - Php

You can simply do this

$data += array($category => $question);

If your're running on php 5.4+

$data += [$category => $question];

Solution 2 - Php

I think you want $data[$category] = $question;

Or in case you want an array that maps categories to array of questions:

$data = array();
foreach($file_data as $value) {
    list($category, $question) = explode('|', $value, 2);

    if(!isset($data[$category])) {
        $data[$category] = array();
    }
    $data[$category][] = $question;
}
print_r($data);

Solution 3 - Php

before for loop :

$data = array();

then in your loop:

$data[] = array($catagory => $question);

Solution 4 - Php

I know this is an old question but you can use:

array_push($data, array($category => $question));

This will push the array onto the end of your current array. Or if you are just trying to add single values to the end of your array, not more arrays then you can use this:

array_push($data,$question);

Solution 5 - Php

For anyone that also need to add into 2d associative array, you can also use answer given above, and use the code like this

 $data[$category]["test"] = $question

you can then call it (to test out the result by:

echo $data[$category]["test"];

which should print $question

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPhilView Question on Stackoverflow
Solution 1 - PhpMohyaddin AlaoddinView Answer on Stackoverflow
Solution 2 - PhpThiefMasterView Answer on Stackoverflow
Solution 3 - PhpmoeView Answer on Stackoverflow
Solution 4 - PhpMikeView Answer on Stackoverflow
Solution 5 - PhpmaximranView Answer on Stackoverflow