使数组值可变 (PHP)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/736201/
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
Make array value variable (PHP)
提问by Ryan
Say I want to echo an array but I want to make the value in the array I echo variable, how would I do this?
假设我想回显一个数组,但我想让数组中的值回显变量,我该怎么做?
Below is kind of an explanation of what I won't to do but it isn't the correct syntax.
下面是对我不会做的事情的解释,但这不是正确的语法。
$number = 0;
echo myArray[$number];
回答by Paolo Bergantino
I'm not sure what you mean. What you have isn't working because you're missing a $in myArray:
我不确定你是什么意思。您所拥有的无法正常工作,因为您缺少一个$in myArray:
$myArray = array('hi','hiya','hello','gday');
$index = 2;
echo $myArray[$index]; // prints hello
$index = 0;
echo $myArray[$index]; // prints hi
Unlike other languages, all PHP variable types are preceded by a dollar sign.
与其他语言不同,所有 PHP 变量类型都以美元符号开头。
回答by Paolo Bergantino
Just to add more. Another type of array is associative array, where the element is determined using some identifier, usually string.
只是为了添加更多。另一种类型的数组是关联数组,其中元素是使用某些标识符(通常是字符串)确定的。
$arrayStates = array('NY' => 'New York', 'CA' => 'California');
To display the values, you can use:
要显示值,您可以使用:
echo $arrayStates['NY']; //prints New York
or, you can also use its numeric index
或者,您也可以使用其数字索引
echo $arrayStates[1]; //prints California
To iterate all values of an array, use foreach or for.
要迭代数组的所有值,请使用 foreach 或 for。
foreach($arrayStates as $state) {
echo $state;
}
Remember, if foreach is used on non-array, it will produce warning. So you may want to do:
请记住,如果在非数组上使用 foreach,它将产生警告。所以你可能想要这样做:
if(is_array($arrayStates)) {
foreach($arrayStates as $state) {
echo $state;
}
}
Hope that helps!
希望有帮助!
回答by Alister Bulman
You are nearly there:
你快到了:
$number = 0;
$myArray = array('a', 'b')
echo $myArray[$number]; // outputs 'a'
回答by John T
$myArray = array("one","two","three","four");
$arrSize=sizeof($myArray);
for ($number = 0; $number < $arrSize; $number++) {
echo "$myArray[$number] ";
}
// Output: one two three four
回答by saw black
$myArray = array('hi','hiya','hello','gday');
for($count=0;$count<count($myArray);$count++)
{
$SingleValue = $myArray[$count];
$AllTogether = $AllTogether.",".$SingleValue;
}

