Hadley8899 Hadley8899 - 2 months ago 6
PHP Question

Adding values to a multidimensional associative array in php

Im trying to build a site messaging system for all of my information messages using an array i can loop through. I am trying to do it so i can separate the messages in the array (Also so they can be added appropriately)

The test code i have is

<?php

$test_messasge = array
(
array("successMessage" => array()),
array("informationMessage" => array()),
array("errorMessage" => array()),
array("warningMessage" => array()),
array("message" => array())
);
var_dump($test_messasge);

echo "<br />";
echo "<br />";

$test_message['message'][] = "I am message 1";
$test_message["message"][] = "I am message 2";
$test_message["errorMessage"][] = "I am errorMessage 1";
$test_message["informationMessage"][] = "I am informationMessage 1";

foreach($test_messasge['message'] as $message){
echo $message . "<br />";
}
echo "<br />";
echo "<br />";
var_dump($test_messasge);

?>


After adding the messages via $test_message['message'][] = "Whatever" in my var dumps it is shown as empty, When i do the loop it get the error "Undefined index: message"

Am i going about this wrong ? Is there a better way to do this rather than using a multidimensional array ?

Cheers in advance
Ryan

Answer

In your loop, please change your variable name $test_messasge to $test_message

foreach ($test_message['message'] as $message){
    echo $message . "<br />";
}
Comments