如何将字符串值添加到 PHP 数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5458061/
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
How to add a string value into a PHP array
提问by souce code
When I add a string value into an array through array_push()
, it gives me a numeric value, i.e.,
当我通过 将一个字符串值添加到一个数组中时array_push()
,它给了我一个数值,即,
$array = array("one", "two", "three");
$array2 = array("test", "test2");
foreach ($array as $value) {
if ($value === 'one') {
$push = array_push($array2, $value);
}
}
print_r($push);
Its output is 3
. I want $array2 = array("test", "test2", "one")
它的输出是3
。我想要$array2 = array("test", "test2", "one")
回答by Shakti Singh
The array_pushis working as it is designed for.
该array_push的工作,因为它是专为。
It will add the value and returns the number of elements in that array.
它将添加该值并返回该数组中的元素数。
so it is natural if it is returning 3 your array has 2 elements after array push there are now three elements.
所以很自然,如果它返回 3 你的数组在数组推送后有 2 个元素,现在有三个元素。
You should print_r($array2)
your array and look the elements.
你应该print_r($array2)
你的数组并查看元素。
回答by mauris
This line:
这一行:
$push = array_push($array2, $value);
Should be just
应该只是
array_push($array2, $value);
array_push()
uses reference to the array for the first parameter. When you print_r()
, you print the array $array2
, instead of $push
.
array_push()
使用对数组的引用作为第一个参数。当你print_r()
,你打印数组$array2
,而不是$push
.
回答by Kirby Todd
You are printing the return value of array_push
which is the number of items in the array after the push. Try this:
您正在打印array_push
推送后数组中项目数的返回值。尝试这个:
<?php
$array = array("one","two","three");
$array2 = array("test","test2");
foreach ($array as $value) {
if ($value === 'one') {
array_push($array2, $value);
}
}
print_r($array2);
回答by Phoenix
Really, you should be using $array2[] = $value;
which will put the value in the first available numeric key in the array, rather than array_push()
.
真的,您应该使用$array2[] = $value;
which 将值放在数组中的第一个可用数字键中,而不是array_push()
.
To get the value of the last element in the array(i.e. what you just added) and keep the array intact, use end($array)
, or to get the last element and remove it from array, use array_pop($array)
要获取数组中最后一个元素的值(即您刚刚添加的元素)并保持数组完整,请使用end($array)
,或获取最后一个元素并将其从数组中删除,请使用array_pop($array)
回答by Sony Santos
array_push modifies $array2. $push contains count($array2).
array_push 修改 $array2。$push 包含 count($array2)。
Check http://php.net/array_push.
回答by Belinda
array_push takes the array by reference and returns the new number of elements in the array, not the new array as described here. That is why you are getting 3. If you want to see the elements in the array use printr($array2);
array_push 通过引用获取数组并返回数组中的新元素数,而不是此处描述的新数组。这就是为什么你得到 3。如果你想查看数组中的元素,请使用printr($array2);