Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove dashes from each value in an array, then rebuild array

Im having a lot of trouble with this, and I'm now 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 is run, i need to remove any dashes from any of the individual array values and replace them with spaces.

This is producing 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 correct way to do this?

Thanks

like image 564
Ricky Mason Avatar asked Jul 13 '26 23:07

Ricky Mason


1 Answers

All of the exploding and imploding isn't really necessary. Nor would you need to create a new array. You can cycle through your values by reference, and modify them in a one-liner:

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

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

Which outputs:

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

Demo: http://codepad.org/up0VoZ21

like image 102
Sampson Avatar answered Jul 15 '26 13:07

Sampson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!