php - How to split spread string inside array
i have array of words and mistakes
$words = ["hi", "my", "name", "is", "john doe"];
i have loop to trim words
foreach ($words as &$w) {
$w = trim($w);
}
but i wanna have final result to be
$words ["hi", "my", "name", "is", "john", "doe"];
having "john" and "doe" trimmed too
i thought using
if (str_contains($w, " ")) {
$w = explode(" ", $string);
}
to clean every word but i do not know how to spread them back and removing old bad value
Answer
Solution:
You can not easily make one array element become two array elements, with that kind of loop. If you don't manipulate the original array by using references, but add the elements to a new result array instead, this will be way easier.
$words = ["hi", "my", "name", "is", "john doe"];
$result = [];
foreach($words as $word) {
$result = array_merge($result, explode(' ', $word));
}
Of course the whole thing could be done even quicker, if you just joined your existing word array with a space between the elements first, and then exploded the result at space again. One-liner:
$words = explode(' ', implode(' ', $words));
Answer
Solution:
$words = [ 'hi', 'my', 'name', 'is', 'john doe' ];
$result = [];
foreach ($words as $word) {
array_push($result, ...explode(' ', trim($word)));
}
print_r($result);
Source