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'];
Accessing the properties of a StdClass()$myNameIs $data->{'name'}; Accessing the whole object called $data. The for-each loop adds it to $array, and then by using the print_r function, it will display everything.
Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property .
As storing value in array is very simple, the accessing value from array is also so simple. You can access array's value by its index position. Each index position in array refers to a memory address in which your values are saved.
If you just want to print you can use var_dump() or print_r() . var_dump($obj); print_r($obj); If you want an array of all properties and their values use get_object_vars() .
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. It's 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 contain other bags too :)
An array contains 'key
' and 'value
' pairs. Providing a key for an array member is optional and in this case it is automatically assigned a numeric key which starts with 0 and keeps on incrementing by 1 for each additional member. We can retrieve a 'value' from the array by it's 'key
'.
So we can define an array in the following ways (with respect to keys):
$colorPallete = ['red', 'blue', 'green'];
The above array will be assigned numeric keys automatically. So the key assigned to red will be 0, for blue 1 and so on.
$colorPallete[0]; // will output 'red' $colorPallete[1]; // will output 'blue' $colorPallete[2]; // will output 'green'
$colorPallete = ['love' => 'red', 'trust' => 'blue', 'envy' => 'green']; // we expliicitely define the keys ourself.
$colorPallete['love']; // will output 'red' $colorPallete['trust']; // will output 'blue' $colorPallete['envy']; // will output 'green'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With