What is the use of “=>” symbol in PHP ?

The ‘=>’ symbol is used to assign key value pairs in an array. The value of left side is called key and the value of right side is called value of key. It is mostly used in associative array.

Syntax:

key => value

Example 1: PHP program to create associative array using ‘=>’ symbol.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
// PHP program to use '=>' symbol
$subject = array( "Maths" => 95,
                  "Physics" => 90, 
                  "Chemistry" => 96,
                  "English" => 93, 
                  "Computer" => 98
            ); 
      
// Accessing the array elements
echo "Marks for students:\n"
echo "Maths:" . $subject["Maths"], "\n"
echo "Physics:" . $subject["Physics"], "\n"
echo "Chemistry:" . $subject["Chemistry"], "\n"
echo "English:" . $subject["English"], "\n"
echo "Computer:" . $subject["Computer"], "\n"
  
?> 

chevron_right


Output:

Marks for students:
Maths:95
Physics:90
Chemistry:96
English:93
Computer:98

Example 2: PHP program to create numeric indexed array using ‘=>’ symbols.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to create numeric
// indexed array
$arr = array( "0" => 7,
              "1" => 10,
              "2" => 8,
              "3" => 5
        );
  
// Display array elements
foreach($arr as $key => $value) {
    echo $key . " => " . $value . "\n";
}
  
?>

chevron_right


Output:

0 => 7
1 => 10
2 => 8
3 => 5

Example 3: PHP program to assign numeric index without using ‘=&gt’ symbol.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
// PHP program to create indexed array
// without using '=>' symbols
$name = array("Zack", "Anthony"
        "Ram", "Salim", "Raghav"); 
  
// Display array elements
foreach($name as $key => $value) {
    echo $key . " => " . $value . "\n";
}
  
?> 

chevron_right


Output:

0 => Zack
1 => Anthony
2 => Ram
3 => Salim
4 => Raghav


My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.