phparrays

Hyphenate all words in an array then implode all elements using a space as glue


I'm trying to manipulate an $array:

Array ([0] => General [1] => Custom Title) 

Using Implode, I can get the $array into individual pieces seperated by a space:

<?php $pieces = implode(" ", $array); ?>

Output:

General Custom Title

However, if the array pieces are two words, it doesn't work as I would prefer the output to be:

General Custom-Title

Solution

  • Replace spaces with hyphens, before you implode.

    foreach ($arr as $idx => $val) {
        $arr[$idx] = str_replace(" ", "-", $val);
    }
    $pieces = implode(" ", $arr);