1

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'??

1
  • a var_dump($values); would be helpful Commented Aug 4, 2014 at 9:52

1 Answer 1

4

-> 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

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)
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.
That's true. Sorry, my bad.
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.
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
|

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.