Home > Software engineering >  Split the text into words and put them in an array
Split the text into words and put them in an array

Time:01-18

Please help the beginner, it is necessary to break the text into words and write them into the array my code now: My code

 <?php
$string = "1 2 3 4 5";
$delim = " ";
$tok = strtok($string, $delim);
while ($tok !== false) {  
  echo "$tok<br>";
   $tok = strtok($delim); 
}
?>  

How to write the result to an array?

CodePudding user response:

This can be very easily done using explode() function, like the following:

$string = "1 2 3 4 5";
explode(' ',$string)

' ' stands for a separator, or simply the key at which the function will cut the string.

Your output will look like this

array(5) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
  [3]=>
  string(1) "4"
  [4]=>
  string(1) "5"
}

Just for more details about this topic, the reverse function here would be implode(), sintax is the following: implode(' ',$array) And again, ' ' stands for separator but within the string, so your output would be 1 2 3 4 5

CodePudding user response:

Sorry, but how to print it in a loop

$string = "1 2 3 4 5";
$ex = explode(' ',$string) ; 
while($ex !== false)
 {
 
 print_r($ex);
}

So it prints out indefinitely

  • Related