0

There is something fundamental I don't understand about PHP arrays. If I create an array and I want to call a value from that array when and why should I use $array->item vs. $array['item']?

My array:

$fruit_qty = array('watermelon' => 3, 'apple' => 5);

If I want the value '5' to print should I use:

echo "Number of Apples: " . $fruit_qty->apple;

vs

echo "Number of Apples: " . $fruit_qty['apple'];

My guess thus far is that $array->item calls a specific value from the array. Whereas, $array['item'] calls and array nested in the array. So I could potentially do $array['sub_array']->value. Is this correct?

1
  • 5
    PHP objects != PHP arrays In your example, you cannot do $fruit_qty->apple, as you would get Notice: Trying to get property of non-object Commented Jun 5, 2013 at 21:59

2 Answers 2

7

-> is an object caller. Since arrays aren't objects then you shouldn't use the -> code.

Using square quotes is the correct way to retrieve an array value.

Sign up to request clarification or add additional context in comments.

2 Comments

Let's assume I had an empty array called $fruit_qty. What would be the difference between $fruit_qty['apple'] = 5; and $fruit_qty->apple = 5;?
@fortmac The -> implies that $fruit_qty is an object and not an array. If you attempted to use -> on an array, you would get an error like Warning: Attempt to assign property of non-object
4

-> applies to objects, [] applies to arrays. They are two completely different operators and should not be confused.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.