0

Im having a problem printing out the values inside a 2d array using echo, it works prefectly using print_r:

print_r($array);

The result of which is :

Array ( [0] => MongoId Object 
( [$id] => 57a789b7ce2350b40e000029 ) [1] => MongoId Object 
( [$id] => 57a72d35ce2350681200002b ) [2] => 3 )

However when i try to access the values using:

echo $similar[0][1];
//or
echo $similar[0][0];

I get the error : 'Cannot use object of type MongoId as array'

I have also tried different types of loops from here incase the error was triggered by accessing the values specifically by element number, however i got the same error and im unsure why. Any help would be appreciated :)

2
  • 1
    Even this doesn't work? echo $array[0]['_id']; echo $array[1]['_id']; Commented Aug 8, 2016 at 14:03
  • Ok no actually made a mistake yes i still get the error for one 'echo $similar[0]['_id'];' , for the second one $similar['_id'][1]; nothing is printed but no error either....which is better but still unsure why Commented Aug 8, 2016 at 14:08

1 Answer 1

1

Since $similar[0] is an MongoId object, and want to access its $id then you must use $similar[0]->{'$id'})

in your example elements 0 and 1 are MongoId objects, while element 2 is an integer of 3.

So this is how you print them all

echo $similar[0]->{'$id'}) # gives 57a789b7ce2350b40e000029
echo $similar[1]->{'$id'}) # gives 57a72d35ce2350681200002b
echo $similar[2] # gives 3
Sign up to request clarification or add additional context in comments.

1 Comment

perfect! Thanks for the tip!

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.