[英]Look for Array key with value if equals php
我想使用mt_random生成一个数字,这就是代码的作用,然后我想查看它是否等于数组中的值以打印出文本版本。
示例:如果结果为2,键[2]为2,则打印“两个”
在此示例中, $nul
是最终输出。
最终在这个论坛上注册! 在此感谢所有这些年来为人们提供帮助的人。 我的第一个问题,所以请不要害我!
我想使用mt_random生成一个数字,这就是代码的作用,然后我想查看它是否等于数组中的值以打印出文本版本。
<?php
$min = 1;
$max = 6;
$array = [
"1" => "one",
"2" => "two",
"3" => "three",
"4" => "four",
"5" => "five",
"6" => "six",
];
if (!isset($_POST["submit"]))
{
$nul = "Druk op gooi";
}
if (isset($_POST["submit"]))
{
$random = mt_rand($min,$max);
$nul = $random;
}
?>
<form action="dobbelen3.php" method="post">
<div class="dobbel" id="dobbelid">
<?php
if(isset($_POST['submit']))
{
echo "<img src='images/$nul.JPG' width='121' height='115' />";
}
?>
</div>
<input type="text" name="Project" value="
<?php
echo $nul;
?>
" style="width:121px;"/>
<input type="submit" name="submit" value="submit" />
</form>
您拥有数组的键,因此只需获取其值即可。
$random = 2;
$string = $array[$random];
您甚至可以使代码更简洁:
$array = ["one", "two", "three", "four", "five", "six"];
$string = $array[$random-1];
默认情况下,数组以0开头,因此$array[0]
将包含“ 1”,这就是为什么需要从所需的实际值中减去1的原因。
$myArr = array('foo', 'bar');
// would be identical to
$myArr = array(0 => 'foo', 1 => 'bar');
这称为基于零的索引
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.