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!

Krt_Malta
  • 9,265
  • 18
  • 53
  • 91

2 Answers2

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);
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);
    }
}
Krt_Malta
  • 9,265
  • 18
  • 53
  • 91
Ayush
  • 41,754
  • 51
  • 164
  • 239
  • 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. – Daniël Voogsgerd May 14 '12 at 17:58