How to store the string values into an array in php?

Member

by domenico , in category: PHP General , 9 months ago

How to store the string values into an array in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 9 months ago

@domenico 

In PHP, you can store string values into an array using the array() function or by using square brackets [] notation.


Here are two examples of how you can store string values into an array:

  1. Using the array() function:
1
2
3
4
5
6
7
// Declare an array using the array() function and store string values
$array = array("value1", "value2", "value3");

// Access array elements using their index
echo $array[0]; // Output: value1
echo $array[1]; // Output: value2
echo $array[2]; // Output: value3


  1. Using square brackets [] notation:
1
2
3
4
5
6
7
// Declare an array using the square brackets [] and store string values
$array = ["value1", "value2", "value3"];

// Access array elements using their index
echo $array[0]; // Output: value1
echo $array[1]; // Output: value2
echo $array[2]; // Output: value3


Note: In PHP, arrays can also dynamically grow and you can add string values to an array using the [] notation as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Declare an empty array
$array = [];

// Add string values to the array
$array[] = "value1";
$array[] = "value2";
$array[] = "value3";

// Access array elements using their index
echo $array[0]; // Output: value1
echo $array[1]; // Output: value2
echo $array[2]; // Output: value3


You can also use other array functions like array_push() or array_merge() to add string values to an existing array.