How to create an array from a PHP string? explain with example

You can use the array() function with comma strings passed as an argument to it, to create an array of strings.

Syntax:-

$arr = array( 
string1, 
string2, 
string3 );

You can use create an empty array first using the array() function and then assign strings using offset. The syntax is

$arr = array();
$arr[0] = "string1";
$arr[1] = "string2";

we will create an empty array and then assign strings as elements to it using index/offset.

<?php
$arr = array();
$arr[0] = "bus";
$arr[1] = "car";
$arr[2] = "trains";
?>

Echo String Array

You can use the echo construct and implode() function to display all elements of the string array to a browser. In the following example, we will display all elements of a string array, separated by a single space.

<?php
   $arr = array(
          "bus",
          "car",
          "trains"
   );

   $arrString = implode(" ", $arr);

   echo $arrString;
?>

Output:-

Iterate over Strings of String Array

To iterate over individual strings of a string array, you can use foreach loop, for loop, while loop, etc. In the following example, we will use a PHP foreach loop to iterate over elements of a string array.

Example:-

<?php
    $arr = array(
       "Maruti",
       "Mahindra",
       "Honda"
    );
    foreach ($arr as $string) {
      echo " " , $string;
    }
?>

Output:-

Related Posts

PHP explode() Function Example Tutorial

A PHP explode function example is given in this article. I will demonstrate how to use PHP’s explode string to array function. This is a basic example…

How to Convert Array to String in PHP?

We will cover the example of converting an array to a string in PHP in this lesson. We’ll examine an example of converting an array to a…

How Can I Convert a String in PHP Into an Array?

We will go over how to transform a string into an array in PHP in this little tutorial. Describe how to convert a string value into an…

How to Use the array_merge() Function in PHP?

We will go over the simple and quick method to use the PHP array_merge() function example in this brief tutorial. Let’s talk about the PHP example of…

How to Merge Two Arrays in PHP?

I explained simply how to merge two arrays in PHP Laravel. you will learn how to append two arrays in PHP. you will learn how to merge…

How to Get the First 5 Elements of Array in PHP?

Here, I will show you the php array to get the first 5 elements. let’s discuss about php array getting 5 first element values. you can see…

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x