Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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

>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));
}

https://3v4l.org/bctuK

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));

https://3v4l.org/ERd3l

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading