How to create associative array in php?

by princess.fritsch , in category: PHP , 2 years ago

How to create associative array in php?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by rollin , 2 years ago

@princess.fritsch You can create associative array in php using by a short syntax [] or array(), below is my example:


1
2
3
4
5
6
7
<?php

// associative array(short syntax)
$array = ["example" => "test", "example2" => "test2"];

// or associative array
$array = array("example" => "test", "example2" => "test2");


Member

by sabryna , a year ago

@princess.fritsch 

To create an associative array in PHP, you can use the array function as follows:

1
2
3
4
5
6
$array = array(
  "key1" => "value1",
  "key2" => "value2",
  "key3" => "value3",
  ...
);


You can also use the short array syntax, introduced in PHP 5.4:

1
2
3
4
5
6
$array = [
  "key1" => "value1",
  "key2" => "value2",
  "key3" => "value3",
  ...
];


You can access the values in the array using the keys, like this:

1
2
echo $array["key1"];  // prints "value1"
echo $array["key2"];  // prints "value2"


You can also use a loop to iterate over the elements of the array and access the keys and values:

1
2
3
4
foreach ($array as $key => $value) {
  echo $key . ": " . $value . "
";
}