Mac Ben Mac Ben - 7 months ago 18
PHP Question

clear string from commas and put it into array

I want clear all commas from string and then put all words separated with comma into array.

For me it's easy to make it in the case i have this type of string:

word1,word2,word3,word4,word5,word6


I have juste to explode them and put them into array like this:

$words = "word1,word2,word3,word4,word5,word6";
$explode = explode(",", $words);

$array = array();
foreach($explode as $word) {
$array[] = $word;
}


And here come my need:
In the case i have this kind of string what is the approch ?

word1,,word2,,,word3,word4,,,,,,,,,,,,word5,,,,word6...


The number of commas between words undefined and can be up to 100 commas.

Let me know if u have good approch to this kind of string.

Answer

The array_filter function in PHP is used for "filtering" an array i.e. making a new array from the elements of an array that satisfy a condition.

By default if we do not pass any callback to array_filter, it removes all falsey and null values. We can send a callback function as a second parameter which returns true for elements that should stay and false for elements that should be removed.

$words = "word1,word2,word3,word4,word5,word6";
$words_arr = array_filter(explode(",", $words));
print_r($words_arr);

If there is whitespace between commas, then:

$words_arr = array_filter(explode(",", $words), function ($e) {
    return strlen(trim($e)) > 0;    // Only select those elements which have a length > 0 after trimming
});

strlen is for getting the string length

trim is for stripping whitespace from the beginning and end of a string

Comments