📜  PHP中“=>”符号有什么用?

📅  最后修改于: 2022-05-13 01:54:11.001000             🧑  作者: Mango

PHP中“=>”符号有什么用?

'=>' 符号用于在数组中分配键值对。左侧的值称为键,右侧的值称为键的值。它主要用于关联数组。

句法:

key => value

示例 1: PHP程序使用“=>”符号创建关联数组。

' 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"; 
  
?> 
输出:
Marks for students:
Maths:95
Physics:90
Chemistry:96
English:93
Computer:98

示例 2: PHP程序使用“=>”符号创建数字索引数组。



 7,
              "1" => 10,
              "2" => 8,
              "3" => 5
        );
  
// Display array elements
foreach($arr as $key => $value) {
    echo $key . " => " . $value . "\n";
}
  
?>
输出:
0 => 7
1 => 10
2 => 8
3 => 5

示例 3: PHP程序在不使用“=>”符号的情况下分配数字索引。

' symbols
$name = array("Zack", "Anthony", 
        "Ram", "Salim", "Raghav"); 
  
// Display array elements
foreach($name as $key => $value) {
    echo $key . " => " . $value . "\n";
}
  
?> 
输出:
0 => Zack
1 => Anthony
2 => Ram
3 => Salim
4 => Raghav