2

Hey guys I can't seem to get the syntax here right, I'm just trying to see if type exists, I've tried

if($obj->type)    /* do something */
if($obj[0]->type) /* do something */
if($obj->type[0]) /* do something */

On this

stdClass::__set_state(
array(
   '0' => 
  stdClass::__set_state(
  array(
     'report_number' => '555',
     'type' => 'citrus',
     'region' => 'Seattle',
     'customer_number' => '9757',
     'customer' => 'The Name',
     'location' => 'West Seattle, WA',
     'shipper' => 'Yamato Transport',
     'po' => '33215',
     'commodity' => 'RARE',
     'label' => 'PRODUCE',
  )),
))

But just can't seem to get it right, I believe it has something to do with [0] being an int instead of varchar but I have no idea....

5
  • Hav you tried $obj->0->type? Commented Feb 22, 2012 at 18:18
  • I'm just guessing, but I would have thought $obj[0]['type'] - have you tried this? Commented Feb 22, 2012 at 18:21
  • 1
    Please try: $obj->{0}->type. Commented Feb 22, 2012 at 18:23
  • $obj = (array)$obj; $obj = (array)$obj[0][0]; echo $obj[0]['type']; Commented Feb 22, 2012 at 18:29
  • $obj->0->type doesn't work, it hates the literal zero for some stupid reason, Hakre that's corr, I figured it out right before I checked the post. Commented Feb 22, 2012 at 18:50

2 Answers 2

9

The output in your question is created by var_export which represents the data of the object as an array. But don't get mislead by that, it's in fact an object.

Object properties are accessed by this syntax:

$obj->property

In your case the property is named 0 which is hard for PHP to deal with in plain code as it's not a property name you could write right away like this:

$obj->0

Instead, you need to tell the PHP parser what the name is by enclosing it into {}:

$obj->{0}

You can then traverse further on to access the type property of 0:

$obj->{0}->type

Hope this is helpful, the question comes up from time to time, this is a related one with more related links: How do I access this object property?.

The PHP Manual has this documented, but not very obvious on the Variable variables entry:

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

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

Comments

0

Have you tried:

<?php
    if (property_exists($obj, 'type')) { 
        // Do something 
    }
?>

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.