Remove dashes from each value in the array, and then rebuild the array

I have a lot of problems with this, and now I'm sure why.

I have a dynamic array that can consist of 1 or more values:

[array] => Array
    (
        [0] => blurb
        [1] => news
        [2] => entertainment
        [3] => sci
        [4] => diablo-3
    )

Here is my model

    public function create_session_filter($filters)
    {
        $array = split("\|", $filters);
        $filter['filter'] = $array;
        $this->session->unset_userdata('filter');
        $this->session->set_userdata($filter);
    }

When the $ array filters start, I need to remove any dashes from any single array value and replace them with spaces.

This leads to some funky results:

    public function create_session_filter($filters)
    {
        $filterarray = array();
        $array = split("\|", $filters);
        foreach ($array as $filter) 
        {
            print_r($filter);
            $filterspace = implode(' ', explode('-', $filter));
            $filterarray = array_push($filterarray, $filterspace);
        }
        $filter['filter'] = $filterarray;
        $this->session->unset_userdata('filter');
        $this->session->set_userdata($filter);
    }

What is the right way to do this?

thank

+3
source share
1 answer

All exploding and exploding are not needed. You also do not need to create a new array. You can iterate over values ​​by reference and change them in one layer:

$array = array( "blurb", "news", "diblo-3" );

$array = str_replace( "-", " ", $array );

What outputs:

Array
(
  [0] => blurb
  [1] => news
  [2] => diblo 3
)

Demo: http://codepad.org/up0VoZ21

+4
source

All Articles