Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Doing print_r() on my array I get the following:

Array ( 
    [0] => 
        stdClass Object 
        ( 
            [id] => 25 
            [time] => 2014-01-16 16:35:17 
            [fname] => 4 
            [text] => 5 
            [url] => 6 
        ) 
)

How can I access a specific value in the array? The following code does not work because of the stdClass Object

echo $array['id'];
share|improve this question
6  
echo $array[0]->id; –  Mark Baker Jan 16 at 17:15
    

3 Answers 3

up vote 9 down vote accepted

To access an array member you use $array['KEY'];

To access an object member you use $obj->KEY;

To access an object member inside an array of objects:
$array[0] // Get the first object in the array
$array[0]->KEY // then access its key

You may also loop over an array of objects like so:

foreach ($arrayOfObjs as $key => $object) {
    echo $object->object_property;
}

Think of an array as a collection of things. Its a bag where you can store your stuff and give them a unique id (key) and access them (or take the stuff out of the bag) using that key. I want to keep things simple here but this bag can contains other bags too :)

share|improve this answer
    
thanks, I thought it would be something simple –  Alex Jan 16 at 17:22
    
hey i didnt understood the use of $value here ..?..and yeah am new to php ..is it a new variable that we create it for finding the key value ? –  Avinash Babu Jan 16 at 17:43
    
@CodeLover if for example we have an array $a = ['someKey' => 'someValue']; then you will get someValue returned if you access $a['someKey']. When we use the foreach loop we can access the key and value for each member of an array. –  Lucky Soni Jul 19 at 7:27
    
@LuckySoni hey i knew it .but i want to know echo $value->KEY ..what does it do ..when i tried in code ..it doesnt echoed anything –  Avinash Babu Jul 19 at 15:03
    
@CodeLover In the answer above the $value is an Object. We are accessing the key on an Object using the Object->key notation. Hope this makes sense. –  Lucky Soni Jul 19 at 18:36

Try this:

echo $array[0]->id;
share|improve this answer

You have an array. A PHP array is basically a "list of things". Your array has one thing in it. That thing is a standard class. You need to either remove the thing from your array

$object = array_shift($array);
var_dump($object->id);

Or refer to the thing by its index in the array.

var_dump( $array[0]->id );

Or, if you're not sure how many things are in the array, loop over the array

foreach($array as $key=>$value)
{
    var_dump($value->id);
    var_dump($array[$key]->id);
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.