1

Can someone explain to me by the most easiest way possible difference between following? After reading about PHP arrays, i still dont get it.

print $myArray[0]->token

and

print $myArray[0]["token"]

Edit:

Question is not about best approach, but about meaning of that. Answer can be fond here, but it is not direct answer to my question

Community
  • 1
  • 1
Fusion
  • 5,046
  • 5
  • 42
  • 51
  • 3
    In the first expression, there is an object on the 0 index of $myArray, in the second, it is an array. – marekful Mar 30 '15 at 11:06
  • Marcell give most simple answer. Remember that second example can also contain object on key 0 that implements array access – imclickingmaniac Mar 30 '15 at 11:10
  • possible duplicate of [PHP Variable vs Array vs Object](http://stackoverflow.com/questions/15521479/php-variable-vs-array-vs-object) – coDe murDerer Mar 30 '15 at 11:10

3 Answers3

2

An example of all this :

<?php

    //Creating simple object

    $bookObject = new stdClass;
    $bookObject->title = "Harry Potter and the Prisoner of Azkaban";

    //Adding object to books array
    $books = array($bookObject);//this array is equivalent to your $myArray

    //Acessing object using -> operator
    echo $books[0]->title;

    //Re-initializng books array
    $books = array(0=>array("title" => "Harry Potter and the Prisoner of Azkaban"));

     //Accessing elements of an array by key
    echo $books[0]['title'];

?>
Whirlwind
  • 14,286
  • 11
  • 68
  • 157
1
  1. $myArray is an array having an object with the property (attribute, variable) named token as its first element.

  2. $myArray is an array having an associative array with the key named token as its first element.

So, it's about two different data structures that the array is holding as the first element indexed by 0.

0
  1. An object inside an array having token element
  2. An array inside an array having token element
Eranda
  • 868
  • 1
  • 10
  • 27