OneBite.Dev - Coding blog in a bite size

Create An Array Of String In PHP

Code snippet for how to Create An Array Of String In PHP with sample and detail explanation

Creating an array of strings in PHP isn’t as daunting as it may seem. With the right information and coding practices, you can quickly handle such tasks and even find them enjoyable.

Creating the Array

We will start by creating an array of strings. Here’s a simple example:

<?php
$fruits = array("Apple", "Banana", "Mango", "Orange", "Papaya");
?>

In this code, we have declared a variable $fruits and assigned an array to it. The array contains five elements, all of which are strings.

Code Explanation

The array keyword in PHP is used to declare an array. This keyword is followed by a pair of round brackets ( ). Within these brackets, we put all the elements that we want in our array. Each element is separated from the other by a comma ,. In our case, the elements are “Apple”, “Banana”, “Mango”, “Orange”, “Papaya”.

These elements are the strings that we want in our array. Therefore, the variable $fruits now holds an array of strings.

We can print the elements of the array using a foreach loop as follows:

<?php
$fruits = array("Apple", "Banana", "Mango", "Orange", "Papaya");

foreach($fruits as $fruit){
  echo $fruit."<br>";
}
?>

In the above code, we are passing each element of the $fruits array to $fruit variable and then printing it. The result will be each fruit written on a new line.

That’s it! We just created an array of strings in PHP. Creating arrays of strings in PHP is very simple and straightforward once you understand the syntax and application of PHP arrays. Keep practicing and make sure to experiment with your own array to familiarize yourself with this concept.

php