Home  >  Article  >  Backend Development  >  How to add variables to php array

How to add variables to php array

PHPz
PHPzOriginal
2023-04-26 09:11:14667browse

PHP is a widely used development language that supports multiple data types, among which arrays are a very commonly used data type. Arrays can be one-dimensional arrays, two-dimensional arrays, or multi-dimensional arrays, and can accommodate different types of data, including numeric types, string types, Boolean types, and so on. In PHP, to add variables to an array, you can use the following two methods:

  1. Use the array_push() function

array_push() function is a PHP built-in function, Used to add one or more elements to the end of an array. This function accepts two parameters, the first parameter is the array to which the element is to be added, and the second parameter is the value to be added to the array.

Sample code:

$my_array = ["apple", "banana", "orange"];
array_push($my_array, "watermelon");
print_r($my_array);

Output result:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => watermelon
)

In the above code, the array_push() function is used to add a string "watermelon" to the $my_array array.

If you want to add multiple elements to the array, just add more values ​​to the second parameter list of the array_push() function.

  1. Assign new values ​​directly to array elements

Array elements in PHP can be accessed through subscripts, and new values ​​can be assigned to arrays using subscripts.

Sample code:

$my_array = ["apple", "banana", "orange"];
$my_array[] = "watermelon";
print_r($my_array);

Output result:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => watermelon
)

In the above code, we use the [] operator to assign the new value "watermelon" to the $my_array array The last element.

It should be noted that if the specified subscript does not exist in the array, a new element will be created. If the subscript already exists, the value of the original element will be overwritten.

Summary

You can easily add variables to a PHP array through the array_push() function or by directly assigning new values ​​to array elements. Both methods work regardless of whether it is a one-dimensional array, a two-dimensional array, or a multi-dimensional array. Which method to use depends on specific logical needs and personal habits. Reasonable use can improve the readability and maintainability of the code.

The above is the detailed content of How to add variables to php array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn