php 带有索引和键的php array_push

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15388641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:08:27  来源:igfitidea点击:

php array_push with index and key

phparray-push

提问by user1269625

I am not sure if I got the terms right in my title, but I am trying to do a php array_pushlike so

我不确定我的标题中的条款是否正确,但我正在尝试做一个array_push像这样的 php

array_push($countryList, "US" => "United States");

but this gives me a syntax error.

但这给了我一个语法错误。

Am I not doing this properly?

我这样做不正确吗?

采纳答案by eL-Prova

Adding like

添加喜欢

$countryList["US"] = "United States";

Pushing a value into an array automatically creates a numeric key for it.

将值推入数组会自动为其创建一个数字键。

When adding a key-value pair to an array, you already have the key, you don't need one to be created for you. Pushing a key into an array doesn't make sense. You can only set the value of the specific key in the array.

将键值对添加到数组时,您已经拥有键,不需要为您创建键。将键推入数组没有意义。您只能设置数组中特定键的值。

// no key
array_push($array, $value);
// same as:
$array[] = $value;

// key already known
$array[$key] = $value

;

;

回答by Faizan Noor

If you want to push a value with key in an array then you may use the following function:

如果要使用数组中的键推送值,则可以使用以下函数:

function array_push_assoc($array, $key, $value){
    $array[$key] = $value;
    return $array;
}

Usage: $array= array_push_assoc($array, 'US', 'United States');

回答by Jong Yun Kim

Try using this array merge method :

尝试使用此数组合并方法:

$countryList = array_merge($countryList, array("US" => "United States"));

回答by Vincent MAURY

Refer to online php doc ...

参考在线php文档...

"US" => "United States" is not a var !

"US" => "United States" 不是 var !