Mike
Mike

Reputation: 2923

How to echo multidimensional array variables using PHP?

This question may be very simple and easy but unfortunately I can't answer it correctly.

I have a data set that I obtained from the database then based on a condition I create a new "data set" or a multidimensional array finally I am ready to display what's in the final array. The reason why I am using a second array if because I need to use it for other purposes.

This is my current code

//$controllers is a data set returned from a mysql query
        $set_controllers = array();
        foreach($controllers AS $input){
            
            $input_value = '';
            
            if(isset($_POST[$input['name']]) ){
                $input_value = trim($_POST[$input['name']]);
            }
        
            $set_controllers[]['name'] = $input['name'];            //name
            $set_controllers[]['answer'] = $input_value;            //answer
            $set_controllers[]['required'] = $input['required'];    //is required field or not
            
        }

    
    foreach($set_controllers AS $field){
    
        echo $field['name'] . '<br />';
        echo $field['required'] . '<br />';
        echo $field['answer'] . '<br /><br />';
    
    }

The problem that I am having is:

Notice: Undefined index: required

Undefined index: name

Undefined index: answer

Why do I get this error? How can I solve it?

Upvotes: 0

Views: 109

Answers (1)

steven
steven

Reputation: 4875

Please try this:

$tmp = array();
$tmp['name'] = $input['name'];            //name
$tmp['answer'] = $input_value;            //answer
$tmp['required'] = $input['required'];    //is required field or not

$set_controllers[] = $tmp;

with [] you create a new index and i think you dont want that for each line.

Upvotes: 7

Related Questions