w3resource

PHP String Exercises: Put a string in an array


12. Convert String to Array (Split by New Line)

Write a PHP script to put a string in an array.

Sample strings: "Twinkle, twinkle, little star,\nHow I wonder what you are.\nUp above the world so high,\nLike a diamond in the sky.";

Visual Presentation:

PHP String Exercises: Put a string in an array

Sample Solution:

PHP Code:

<?php
// Define a multi-line string containing the lyrics of a song
$str = "Twinkle, twinkle, little star,\nHow I wonder what you are.\nUp above the world so high,\nLike a diamond in the sky.";

// Explode the multi-line string into an array using "
" as the delimiter $arra1 = explode("<br>", $str); // Display the array containing the lines of the song var_dump($arra1); ?>

Output:

array(1) {                                                  
  [0]=>                                                     
  string(112) "Twinkle, twinkle, little star,               
How I wonder what you are.                                  
Up above the world so high,                                 
Like a diamond in the sky."                                 
}  

Explanation:

In the exercise above,

  • It defines a multi-line string variable $str, which contains the lyrics of a song. Each line is separated by the newline character \n.
  • It uses the "explode()" function to split the multi-line string $str into an array $arra1. The delimiter used for splitting is <br>, which implies that the function is attempting to split the string at occurrences of <br>.
  • Finally, it displays the contents of the array $arra1 using var_dump(), which shows each element of the array (i.e., each line of the song) along with its index.

Flowchart :

Flowchart: Put a string in an array

For more Practice: Solve these Related Problems:

  • Write a PHP script to convert a multi-line string into an array, trimming whitespace from each line and removing empty lines.
  • Write a PHP function that splits a text block by newline characters and returns an array of non-empty trimmed lines.
  • Write a PHP program to read a block of text, convert it to an array, and then output the array structure using var_dump().
  • Write a PHP script to split a paragraph into an array of sentences based on the period delimiter, removing any extra whitespace.

Go to:


PREV : Find First Character Difference Between Strings.
NEXT : Extract Filename Component from URL.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.