PHP is a widely used server-side scripting language for creating dynamic web pages and web applications. Arrays are a very useful data type for storing multiple values. In PHP, we can store variables in arrays to make it easier to access and use these variables. In this article, we will explore how to write variables into a PHP array.
1. Create an array
In PHP, you can use the array() function to create an array, or you can directly declare the array in a variable. The following are two methods of creating an array:
Method one:
$my_array = array();
Method two:
$my_array = [];
2. Write variables into the array
Put variables There are many ways to write to an array, a few of which are described below.
1. Assignment through $key
The following is a common method to write variables into an array by assigning the variable to the specified $key of the array:
$my_array["key1"] = $variable1; $my_array["key2"] = $variable2; $my_array["key3"] = $variable3;
In this example, $variable1, $variable2 and $variable3 are the variables to be stored in the array. These variables can be stored in an array by assigning them to the specified $key of $my_array.
2. Use the array_push() function
Another way is to use the array_push() function to push the variable to the end of the array, as shown below:
$my_array = array(); array_push($my_array, $variable1, $variable2, $variable3);
In this In the example, $variable1, $variable2 and $variable3 are the variables to be stored in the array. Use the array_push() function to add them to the end of $my_array.
3. Use simplified syntax
Another way is to use simplified syntax in PHP. Here is an example:
$my_array = [ "key1" => $variable1, "key2" => $variable2, "key3" => $variable3 ];
In this example, the variables $variable1, $variable2 and $variable3 are assigned to the $key specified in $my_array using simplified syntax.
3. Access variables in arrays
Once variables are stored in an array, they can be accessed using their $key. The following are some examples:
echo $my_array["key1"]; // 输出变量1的值 echo $my_array["key2"]; // 输出变量2的值 echo $my_array["key3"]; // 输出变量3的值
4. Delete variables in the array
If you want to delete variables from the array, you can use the unset() function, as shown below:
unset($my_array["key3"]); // 删除变量3
In this example, use the unset() function to delete the variable with the key name "key3" in the $my_array array.
Summary
Array is a very useful data type in PHP that can store multiple variables and other data. The process of storing variables in an array can be done in different ways, but the way of accessing and using the variables is the same. If you need to delete variables in the array, you can use the unset() function. Hope this article helped you understand how to store variables in PHP arrays.
The above is the detailed content of How to write variables into an array in php. For more information, please follow other related articles on the PHP Chinese website!