首页 > 解决方案 > 在PHP中定义数组时使用双箭头和单冒号有什么区别

问题描述

我通常使用

 $header = array(
    'Content-type: application/json',
    'x-app-key: 123'
 );

定义一个数组,有时我使用

$header = array(
    'Content-type' => 'application/json',
    'x-app-key' => '123'
);

有时一种有效,另一种无效。

请问这两种在PHP中定义数组的方法有什么区别?谢谢你。

标签: php

解决方案


这是完全不同的。当你使用

 $header = array(
    'Content-type: application/json',
    'x-app-key: 123'
 );

你只是在定义一个字符串数组。数组将是

array(2) { 
    [0]=> string(30) "Content-type: application/json" 
    [1]=> string(14) "x-app-key: 123" 
}

但如果你使用

$header = array(
    'Content-type' => 'application/json',
    'x-app-key' => '123'
);

您将创建一个关联数组,就像这样

array(2) { 
     ["Content-type"]=> string(16) "application/json" 
     ["x-app-key"]=> string(3) "123" 
}

请参阅文档以获取完整说明

希望能帮助到你!


推荐阅读