Create an associative array in PHP

Learn, what is an associative array and how to create an associative array in PHP? By IncludeHelp Last updated : December 19, 2023

Prerequisites

To understand this example, you should have the basic knowledge of the following PHP topics:

PHP - Associative Array

In an associative array, we can specify the values with the keys. Then, following two things are required to create an associative array: 1) key, and 2) value

key can be used as an index to access the value from the array.

Note: To create an associative or other types of array, we use array() function.

Syntax

    array(key1=>value1, key2=>value2, key3=>value3, ...);

PHP code to create an associative array

In this example, we are creating an associative array, printing the values: 1) Using keys, and 2) Printing complete array with keys & values

<?php
//creating student array with keys & values
$std = ["id" => "101", "name" => "Amit", "course" => "B.Tech"];

//printing elemenets
print "std elements...\n";
print "Id = " .
    $std["id"] .
    " Name = " .
    $std["name"] .
    " Course = " .
    $std["course"];

//printing array using for each loop

//printing complete array
print "std...\n";
print_r($std);
?>

Output

std elements...
Id = 101 Name = Amit Course = B.Techstd...
Array
(
    [id] => 101
    [name] => Amit
    [course] => B.Tech
)

PHP Array Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.