I'm trying to extract values from an array within an array. The code I have so far looks like this:
$values = $request->request->get('form');
$statusArray = array();
foreach ($values->status as $state) {
array_push($statusArray, $state);
}
The result of doing a var_dump on the $values field is this:
array (size=2)
'status' =>
array (size=2)
0 => string 'New' (length=9)
1 => string 'Old' (length=9)
'apply' => string '' (length=0)
When running the above I get an error basically saying 'status' isn't an object. Can anyone tell me how I can extract the values of the array within 'status'??
asked Aug 4, 2014 at 9:47
maloney
1,6833 gold badges26 silver badges52 bronze badges
1 Answer 1
-> it's the notation to access object values, for arrays you have to use ['key']:
foreach ($values['status'] as $state) {
array_push($statusArray, $state);
}
Object example:
class Foo {
$bar = 'Bar';
}
$foo = new Foo();
echo $foo->bar // prints "bar"
Sign up to request clarification or add additional context in comments.
6 Comments
Tibor B.
So what's wrong with using
->? His get('form') function can still return an object, and he can use it in his loop: foreach ($values->status as $state)Ende Neu
Actually if you see the
var_dump it says that get('form')returns an array, if it would have returned an object you could have used the -> notation like you suggested otherwise this kind of notation is not defined for arrays and you will incur in exceptions.Tibor B.
That's true. Sorry, my bad.
Ende Neu
If you don't know what kind of variable you are getting back, you can use
is_array or is_object to determine which kind of access operator to use.maloney
Thanks for the responses. Is it possible to do a null check on the array? For example, status may not always exist within the array. I tried to do something like this: 'if ($values['status'] != null){' but just get a Undefined index: status error
|
lang-php
var_dump($values);would be helpful