0

I'm quite new to PHP and coming from a Java background. So here it goes:

I have this code:

$selected = array();
foreach($this->getSelectedOptions() AS $array) {
   array_push($selected, $array['value']);
}
var_dump($selected);

getSelectedOptions() retrieves an array of arrays containing strings.

The result is

array
  0 => string 'abc, def' (length=31)

I was expecting something like this though:

Array
(
    [0] => abc
    [1] => def
)

Why is this happening? How can I make my array look like the latter (without doing any post-processing with commas etc.)

Thanks!

2
  • Seems that $array['value'] isn't actually an array (is this coming from a database?). You may need to explode(',', $array['value']);. Commented May 14, 2012 at 17:53
  • What is output of var_dump($this->getSelectedOptions())? Commented May 14, 2012 at 17:56

2 Answers 2

1

This is because the getSelectedOptions() gives you a comma seperated string instead of an array. We don't have the function so we can't do anything with that. The only thing that is possible now is post-processing. Here is some PHP doing the post-processing.

$selected = array();
foreach($this->getSelectedOptions() AS $array) {
   $values = explode(', ', $array['value']);
   array_push($selected, $values);
}
var_dump($selected);
Sign up to request clarification or add additional context in comments.

Comments

0

You need to split the comma separated values and loop again like below:

$selected = array();
foreach($this->getSelectedOptions() AS $array) {
    //$array now contains comma seperated values
    //split and loop
    $values = explode(',',$array['value']);
    foreach($values as $value) {
        array_push($selected, $value);
    }
}

1 Comment

You're mixing up the variables in the loop. You're exploding an array now and for each value that comes out of the exploded array you're adding the entire string into the array.

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.