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

Associative Array in PHP?

An associative array is a simple and very important array of PHP. This array is also used the most, it is very easy to understand this array,…

How to work in functions PHP?

If there is any task in your program which you train to execute repeatedly then instead of writing the code for that task at a different place…

For Loofs in PHP

In for-loop initialization, condition and increment happen on the same line. The loop keeps on repeating as long as the condition is true. When the for loop…

If Else Conditionals in Php?

If Else statement is the most important feature of any programming language, PHP is used to run any Code Of Block according to If Else conditions. This…

What are operators in PHP? PHP – Operator Types

Operators are used to developing data. In Programming Languages, Operators are taken from Mathematics and Operator Programmers work with Data. An operator is a chain of symbols…

String Functions in PHP?

When many characters are written together in sequence, they form a string. For example, India is a string. It is made up of i, n, d, i,…

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