Home > Backend Development > PHP Problem > How to add a value to an array in php

How to add a value to an array in php

PHPz
Release: 2023-04-20 15:12:56
Original
900 people have browsed it

In PHP, adding a new value to an array is very simple and straightforward.

Method 1: Use array brackets plus new key-value pairs

Syntax:

$arrayName['key'] = 'value';
Copy after login

Example:

$fruits = array("apple", "banana", "orange");
$fruits["watermelon"] = "red";
print_r($fruits);
Copy after login

Output:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [watermelon] => red
)
Copy after login

In the above code, $fruits["watermelon"] = "red"; adds a new key-value pair "watermelon" => "red" $fruits in the array.

Method 2: Using PHP’s array_push() function

Syntax:

array_push($arrayName, 'value');
Copy after login

Example:

$fruits = array("apple", "banana", "orange");
array_push($fruits, "watermelon");
print_r($fruits);
Copy after login

Output:

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

In In the above code, array_push($fruits, "watermelon"); adds a new element "watermelon" to the end of the $fruits array.

Method 3: Use PHP’s [] to add directly to the end of the array

This method is only applicable to PHP 5.4 or higher.

Syntax:

$arrayName[] = 'value';
Copy after login

Example:

$fruits = array("apple", "banana", "orange");
$fruits[] = "watermelon";
print_r($fruits);
Copy after login

Output:

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

In the above code, $fruits[] = "watermelon" ; Added a new element "watermelon" to the end of the $fruits array.

No matter which method you choose, adding new values ​​to a PHP array is very simple.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template