In PHP, array is one of the very important data types. Arrays can be used to store one or more values in a variable.
Arrays are divided into the following two types:
In this article, we will focus on how to write one-dimensional arrays in PHP.
Creating a one-dimensional array
In PHP, you can use the following syntax to create a one-dimensional array:
$array_name = array(value1, value2, value3, …);
In this syntax, $array_name is the array you want to The named names, value1, value2, value3, etc. are the values you want to store in the array.
If you want to store a string, you can use the following syntax:
$array_name = array("value1", "value2", "value3", …);
Here is an example of creating a one-dimensional array:
$num_array = array(10, 20, 30, 40, 50); $str_array = array("PHP", "Java", "Python", "C++");
Accessing array elements
Once you create an array, you can use indexing to access array elements. In PHP, indexing starts from 0.
The following is an example of how to access array elements using indexing:
$num_array = array(10, 20, 30, 40, 50); echo $num_array[0]; // 输出 10 echo $num_array[1]; // 输出 20 echo $num_array[2]; // 输出 30 echo $num_array[3]; // 输出 40 echo $num_array[4]; // 输出 50
Looping through an array
In PHP, you can use the following looping structure to iterate over a one-dimensional array:
The following is an example of using a for loop to traverse a one-dimensional array:
$num_array = array(10, 20, 30, 40, 50); for($i = 0; $i < count($num_array); $i++) { echo $num_array[$i] . " "; }
The following is an example of using a foreach loop Example of traversing a one-dimensional array:
$str_array = array("PHP", "Java", "Python", "C++"); foreach($str_array as $value) { echo $value . " "; }
Array sort
In PHP, you can sort a one-dimensional array using the following function:
The following is an example of sorting a one-dimensional array:
$num_array = array(10, 50, 40, 30, 20); sort($num_array); // 升序排序 print_r($num_array); $str_array = array("PHP", "Java", "Python", "C++"); rsort($str_array); // 降序排序 print_r($str_array);
Summary
In PHP, using arrays is a very convenient way to store and Data processing. This article explains how to create, access, iterate, and sort one-dimensional arrays. I hope this article helps you better understand the usage of one-dimensional arrays.
The above is the detailed content of Let's talk about how PHP declares and operates one-dimensional arrays. For more information, please follow other related articles on the PHP Chinese website!