Tags
Asked 2 years ago
9 Jun 2021
Views 226
eclipse-learner

eclipse-learner posted

How to declare an associative array in PHP using array() ?

How to declare an associative array in PHP using array() ?
Nilesh

Nilesh
answered Apr 26 '23 00:00

In PHP, an associative array can be declared using the array () function or using the square bracket syntax []. To declare an associative array using the array() function, you can provide key-value pairs as arguments to the function, like this:

php
Copy code
$my_array = array(
"key1" => "value1",
"key2" => "value2",
"key3" => "value3"
);
This will create an associative array with three key-value pairs. You can access the values of the array using their keys, like this:



echo $my_array["key1"]; // output: value1
echo $my_array["key2"]; // output: value2
echo $my_array["key3"]; // output: value3

You can also add new key-value pairs to the array using the square bracket syntax, like this:



$my_array["key4"] = "value4";

This will add a new key-value pair to the array with key "key4" and value "value4".
Post Answer