EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Associative Array in PHP 

Home » Software Development » Software Development Tutorials » PHP Tutorial » Associative Array in PHP 

Associative Array in PHP 

Introduction on Associative Array

An array is a collection of similar and dissimilar data types. An array stores in a variable related data. We need arrays to create and store these many numbers of variables value in one variable. There are three types of array in PHP. Numeric Arrays, Associative Arrays, and Multidimensional Arrays. An associative array is in the form of key-value pair, where the key is the index of the array and value is the element of the array. Here the key can be user-defined. It is similar to the numeric array, but the keys and values which are stored in the form of a key-value pair.

In this topic, we are going to learn about the Associative Array in PHP.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax

//First Way
$input = array("key1"=>"value1", "key2"=>"value2", "key3"=>"value3");
//Second Way
$input["key1"] = value1;
$input["key2"] = value2;
$input["key3"] = value3;

where $input is the array name, key1 is the index of the array element and value1 is the value of the array element

How to Create an Associative Array in PHP?

The associative array is declared using an array keyword. The key value in the array is declared using ‘=>’ arrow. There are two ways to create an associative array.

Following are the example

Code:

<?php
// create associative array
// first way
$family = array("father" => "Mohan", "mother"=>"Sita", "son"=> "Raj" ,"daughter"=> "Mona");
// second way
$family["father"] = "Mohan";
$family["mother"] = "Sita";
$family["son"] = "Raj";
$family["daughter"] = "Mona";
?>

How to Traverse Associative Array in PHP using various methods

There are two methods through which we can traverse the associative array. One is the foreach loop and the second is for a loop.

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,694 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

Method #1

In this example, an array is declared and named as a $family. This array is in the key-value form where the keys are names of relations like Father, Mother, Son, Daughter. And each key holds the name of the relationship like the first value for index Father is Mohan, the second value for index Mother is Sita, the third value for index Son is Raj, the fourth value for index Daughter is Mona. To traverse this array we use a foreach loop, in which we print both keys as Father, Mother, Son, Daughter and values as Mohan, Sita, Raj and Mona of the array.

Code:

<?php
//example of the associative array
$family = array("father" => "Mohan", "mother"=>"Sita", "son"=> "Raj" ,"daughter"=> "Mona");
//first method to traverse the associative array
foreach($family as $key=>$value) {
echo $key .' is '.$value;
echo '<br>';
}
?>

Method #2

In this example, we will use the same array family as in the previous example and traverse using for loop. Also, we will be using array_keys function to get the keys of the array which are father, mother, son, and daughter. These keys are returned in the form of an array. The array_keys function takes an input array as the parameter and outputs an indexed array. Now to iterate through this loop, we will use for loop and print the keys and values as required.

Code:

 <?php
// Example to demonstrate for loop
$family = array("father" => "Mohan", "mother"=>"Sita", "son"=> "Raj" ,"daughter"=> "Mona");
$length = count($family);
$keys = array_keys($family);
// for loop to traverse associative array
for($i=0; $i<$length; $i++) {
echo "<br>". $keys[$i] . " => " . $family[$keys[$i]];
}
?>

Output:

Associative Array in PHP output 1

Advantages of Associative Array in PHP

  1. There are different functions that work to merge two associative arrays.
  2. It is similar to the user list, stack, queue, etc.
  3. Indexes in the array are used which are helpful in remembering the data
  4. These indexes are user-defined and can be changed accordingly.
  5. The superglobal arrays like $_POST, $_GET, $_SESSION arrays also support associative arrays.

Sorting of Associative Array by Value in PHP

An associative array can be sorted in two ways based on the key and based on value. Here we will learn about sorting the associative array by value. There are two inbuilt php functions like asort() and arsort() which are used for sorting of the associative array by value in alphabetical order.

Let’s learn this with an example.

1. asort(): performs a sort on associative array according to the value in ascending order

Code:

<?php
// example to demonstrate asort() function on associative array by value in ascending order
$family = array("father" => "Mohan", "mother"=>"Sita", "son"=> "Raj" ,"daughter"=> "Mona");
print_r($family);
asort($family);
echo "<br>";
print_r($family);
?>

Output:

Associative Array in PHP output 2

2. arsort(): performs a sort on associative array according to the value in descending order

Code:

<?php
// example to demonstrate asort() function on associative array by value in descending order
$family = array("father" => "Mohan", "mother"=>"Sita", "son"=> "Raj" ,"daughter"=> "Mona");
echo "<br>Before Sort";
print_r($family);
arsort($family);
echo "<br>After Sort";
print_r($family);
?>

Output:

Associative Array in PHP output 3

Sorting of Associative Array by Key in PHP

As associative array can be sorted by value in ascending order. In a similar way, the associative array can be sorted by key alphabetically both in ascending order and in descending order as shown in the below example

1. ksort(): performs a sort on associative array according to the key in ascending order

Code:

<?php
// example to demonstrate ksort() function on associative array by key in ascending order
$family = array("father" => "Mohan", "mother"=>"Sita", "son"=> "Raj" ,"daughter"=> "Mona");
echo "<br>Before Sort";
print_r($family);
ksort($family);
echo "<br>After Sort";
print_r($family);
?>

Output:

php output 4

2. krsort(): performs a sort on associative array according to the key in descending order

Code:

<?php
// example to demonstrate krsort() function on associative array by key in descending order
$family = array("father" => "Mohan", "mother"=>"Sita", "son"=> "Raj" ,"daughter"=> "Mona");
echo "<br>Before Sort";
print_r($family);
krsort($family);
echo "<br>After Sort";
print_r($family);
?>

Output:

php output 5

Conclusion

Programs starting from basic like the syntax, the creation of the array, how to traverse through the array is explained. Also, topics like advantages of the associative array and how to perform sorting on the associative array are also mentioned.

Recommended Articles

This is a guide to Associative Array in PHP. Here we discuss how to create an Associative Array, Traverse Associative Array in PHP and sorting Arrays by value and key. You may also look at the following article to learn more –

  1. Sessions in PHP
  2. Palindrome in PHP
  3. Object in PHP
  4. Overloading in PHP
  5. Complete Guide to Sorting in C# with Examples
  6. C++ Data Types
  7. Python Overloading
  8. Palindrome in JavaScript
  9. Classifying Two Type in Hive Data Type
  10. Top 3 Examples of C# Multidimensional Arrays

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More