String
listIn PHP programs we often need to create lists of strings. We need to add more strings in a dynamic way, as program logic proceeds. The array()
syntax is useful here.
Once we create a string
list in PHP, we will want to iterate over it. The foreach
-loop goes from the first to the last element.
To begin, we create 2 string
lists and populate them with elements. We keep this example simple, but show 2 different initialization syntax forms.
array()
syntax. We pass 3 string
elements to the initializer and the result has 3 elements.short
syntax for creating string
lists (arrays) and because it is easier to read, it should be preferred.// Version 1: syntax for list of 3 strings. $array1 = array("bird", "frog", "cat"); var_dump($array1); // Version 2: another syntax. $array2 = ["bird", "frog", "cat"]; var_dump($array2);array(3) { [0]=> string(4) "bird" [1]=> string(4) "frog" [2]=> string(3) "cat" } array(3) { [0]=> string(4) "bird" [1]=> string(4) "frog" [2]=> string(3) "cat" }
To continue, we use the foreach
-loop to iterate over the string
elements. Consider a string
list of 3 elements—the loop body will be repeated 3 times.
string
list with the short, simple syntax—3 elements are present upon creation.foreach
to iterate over the elements in the string list. Each string
(and its length) is printed with var_dump()
.// Part 1: create string list of 3 strings. $systems = ["linux", "mac", "windows"]; // Part 2: use foreach and display the strings. foreach ($systems as $test) { var_dump($test); }string(5) "linux" string(3) "mac" string(7) "windows"
Append
string
We can append a string
to a string
list as well in PHP. We use the special "append" syntax, which adds an index past the last current index.
$letters = ["a", "b"]; // Append the value 30 to the list. $letters[] = "c"; $letters[] = "d"; var_dump($letters);array(4) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" [3]=> string(1) "d" }
Reverse
exampleOccasionally we may want to reverse the ordering of a string
list in PHP. To do this, we can invoke the array_reverse
function on a string
array.
$words = ["one", "two"]; // Reverse the words in the string array. $result = array_reverse($words); var_dump($result);array(2) { [0]=> string(3) "two" [1]=> string(3) "one" }
In PHP we implement a string
list with an array—but the array type has other features. It can be used as an associative array (a hash) as well.
Using string
lists in PHP is nearly universal—most programs will need to store collections of strings. Important program logic relies upon strings.