Thursday, October 23, 2025
HomeLanguagesHow to create an array with key value pairs in PHP?

How to create an array with key value pairs in PHP?

PHP offers us a special type of array called an Associative Array that allows us to create an array with Key-Value pairs. The syntax for creating an Associative Array is as follows:

Syntax 1: Using array() constructor

$arrayVariable = array(
    key1  => value1,
    key2 => value2,
    key3 => value3,
    ...
    keyN => valueN,
);

Syntax 2: Using shorthand notation

$arrayVariable = [
    key1  => value1,
    key2 => value2,
    key3 => value3,
    ...
    keyN => valueN,
];

Note:

  1. The comma after the last Key-Value pair is optional.
  2. The Key can be of either integer or string type.
  3. The Value can be of any valid type.
  4. If the type of Key is other that string or integer, it will be cast to string or integer depending on the type of Key.

Example 1: Using array() constructor




<?php
$websites = array(
    "Facebook" => 
"Facebook, Inc. is an online social media and
 social networking service company.",
    "Twitter" => 
"Twitter is a microblogging and social networking service on 
which users post and interact with messages known as tweets.",
    "LinkedIn" => 
"LinkedIn is a business and employment-oriented service
 that operates via websites and mobile apps.");
      
$websites["Instagram"] = "Instagram is a photo and video-sharing 
social networking service owned by Facebook, Inc.";
foreach ($websites as $key => $value) {
    echo "<p>$key: $value <p>";
}
?>


Output:
Associative Arrays in PHP

Example 2: Using shorthand notation




<?php
$websites = [
    "Facebook" => 
"Facebook, Inc. is an online social 
    media and social networking service company.",
      
    "Twitter" => "Twitter is a microblogging and social networking service 
    on which users post and interact with messages known as tweets.",
      
    "LinkedIn" => "LinkedIn is a business and 
    employment-oriented service that operates via websites and mobile apps."];
      
$websites[
    "Instagram"] = "Instagram is a photo and video-sharing 
    social networking service owned by Facebook, Inc.";
foreach ($websites as $key => $value) {
    echo "<p>$key: $value <p>";
}
?>


Output:
Associative Arrays in PHP

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS