0

I am facing a strange problem. It may just be a silly mistake, and I am just missing some basics.

I'm running php 5.6.1 on MAMP.

I have a simple array which I get from a mysql query. Using a foreach loop, I can print_r() each value, which gives me: stdClass Object ( [srno] => 6 [link] => this-is-link )

Now I can echo $obj->srno, and that prints fine. But I can't use echo $obj['srno'] which I was previously using, on an older version of PHP, but- It shows nothing.

Any help really appreciated. Thanks!

4
  • 11
    PHP classes are not normally accessible as arrays, only those which implement ArrayAccess Commented Nov 14, 2014 at 18:33
  • 1
    You are getting an array of stdClassobjects and you can't access stdClass object's property like array. If your query returns an array of arrays then you are able to access that as an array, so the question is what are you using for your DB query? Probably you can change the return type to Array instead of stdClass. Commented Nov 14, 2014 at 18:42
  • 1
    -> in PHP is not a pointer !!! Commented Nov 14, 2014 at 18:52
  • @LorenzMeyer yeah, but couldn't find exact word. @TheAlpha I am using codeIgniter result() to return rows. I am sure I was able to use the same code before. Something changed in php 5.6.1? Commented Nov 15, 2014 at 4:41

2 Answers 2

1

If you have a stdClass object and need to address it as an array, you can cast it to array quite easily:

$someObj = new stdClass();
$someObj->foo = "bar";

$someArray = (array)$someObj; // Cast the object to an array

echo $someArray['foo']; // Will give you "bar"

Working example: http://3v4l.org/nni1Y

Of course as comments already pointed out, you may want to look at retrieving your mysql results as an array in the first place.

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

Comments

0

As you said your results return as an object so you can use it by using $obj->your_field_name to display field value. But your can not use by $obj['field_name'];

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.