Home  >  Article  >  Backend Development  >  How to Split a User Input String into an Array in PHP?

How to Split a User Input String into an Array in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-24 00:35:02921browse

How to Split a User Input String into an Array in PHP?

Separate Words into an Array from User Input String

When dealing with user input often times a user will enter multiple words separated by spaces. Knowing how to take those words and split them into an array can be useful in working with the input in your program.

In PHP, you can use the explode() function to split a string into an array based on a delimiter. In your case, you can use explode(" ", $string) to split the string at each space.

Here's an example:

<code class="php">// Assume $input contains the user input string
$words = explode(" ", $input);

// Now you can loop through the $words array
foreach ($words as $word) {
  echo $word . "<br>";
}</code>

Output:

foo
bar
php
js

This example will split the string at each space and store each word in the $words array. You can then loop through the array to access each word individually.

The above is the detailed content of How to Split a User Input String into an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn