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

How to add a value to an array in php

PHPz
PHPzOriginal
2023-04-20 15:07:49811browse

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';

Example:

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

Output:

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

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');

Example:

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

Output:

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

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';

Example:

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

Output:

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

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!

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