Home » PHP » PHP Examples

Create an associative array in PHP

PHP associative array creation: Here, we are going to learn how to create an associative array in PHP?
Submitted by IncludeHelp, on February 07, 2019

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, ...);

Example:

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 = array('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
)




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.