How to add a value to an array in php
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
