Search code examples
phparraysinitializationarray-push

(PHP) Initialize empty multidimensional array and then fill it


I want to create an array with 3 types of information: name, id, and work. First I want to just initialize it, so that I can later fill it with data contained in variables.

I searched how to initialize a multidimensional array, and how to fill it, and that's what I came up with:

$other_matches_info_array = array(array());

$other_matches_name = "carmen";
$other_matches_id = 3;
$other_matches_work = "SON";

array_push($other_matches_info_array['name'], $other_matches_name);
array_push($other_matches_info_array['id'], $other_matches_id);
array_push($other_matches_info_array['work'], $other_matches_work);

This is what I get when I print_r the array:

Array
(
  [0] => Array
    (
    )
  [name] =>
)

What did I do wrong?


Solution

  • very short answer:

    $other_matches_info_array = array();
    // or $other_matches_info_array = []; - it's "common" to init arrays like this in php
    
    $other_matches_name = "carmen";
    $other_matches_id = 3;
    $other_matches_work = "SON";
    
    $other_matches_info_array[] = [ 
        'id' => $other_matches_id,
        'name' => $other_matches_name
    ];
    // so, this means: new element of $other_matches_info_array = new array that is declared like this.