PHP String Exercises: Put a string in an array
PHP String: Exercise-12 with Solution
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:
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 :
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a PHP script to find the first character that is different between two strings.
Next: Write a PHP script to get the filename component of the specified path.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/php-exercises/php-string-exercise-12.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics