skip to Main Content

What is the difference between:

 $data = array("id"=>1,"name"=>"Rock");

And

$data[] = array("id"=>1,"name"=>"Rock");

2

Answers


  1. Your first expression intialises a new variable as an array

    $data = array("id"=>1,"name"=>"Rock");
    print_r($data);
    

    Results:

    Array
    (
        [id] => 1
        [name] => Rock
    )
    

    Your second version appends data to an existing array. Let’s imagine you already have an array $data with some content:

    $data = array('some', 'initial', 'data', 'here');
    

    Then you append some data and show the result:

    $data[] = array("id"=>1,"name"=>"Rock");
    print_r($data);
    

    Results:

    Array
    (
        [0] => some
        [1] => initial
        [2] => data
        [3] => here
        [4] => Array
            (
                [id] => 1
                [name] => Rock
            )
    
    )
    
    Login or Signup to reply.
  2. $data = array("id"=>1,"name"=>"Rock");

    array = [
            "id" => 1,
            "name" => "rock"
    ];
    
    $data = array("id"=>1,"name"=>"Rock");
    
    array = [
            "id" => 1,
            "name" => "rock"
    ];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search