Open In App

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

Last Updated : 23 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In PHP, an array with key-value pairs is called an associative array. It maps specific keys to values, allowing you to access elements using custom keys rather than numerical indices. Keys are strings or integers, while values can be of any data type.

Here we have some common approaches to create an array with key value pairs in PHP:

Approach 1: Basic Key-Value Pair Creation and Iteration

In this approach, we create an associative array where the keys represent social media platforms, and the values are descriptions of these platforms. After adding a new element, we loop through the array and display each key-value pair in an HTML paragraph.

Example 1: In this example we creates an associative array $websites with social media platforms as keys and their descriptions as values. It then adds “Instagram” and loops through the array, printing each key-value pair in paragraph tags.

<?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

Approach 2: Shorthand Array Syntax with Additional Features

In this approach, we utilize the shorthand notation for arrays and add extra key-value pairs dynamically. This method also demonstrates how different data types can be used as values.

Example 2: In this example we defines an associative array of social media platforms and their descriptions, adds Instagram, and loops through the array, printing each key-value pair in paragraphs.

<?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


Next Article

Similar Reads

three90RightbarBannerImg