[英]PHP - Echo variable with a random number?
Given the 3 variables below, each ending in a number. 给定以下3个变量,每个变量均以数字结尾。 I want to echo
out a random one of them by using the mt_rand(1,3)
at the end of $fruit
, so php randomly outputs one of the 3. 我想echo
通过使用了它们的随机的一个mt_rand(1,3)
在结束$fruit
,所以PHP随机输出3中的一个。
<?php
$fruit1 = 'apple';
$fruit2 = 'banana';
$fruit3 = 'orange';
echo $fruit.mt_rand(1,3);
I can do it easily with an array, but I want to know how to get the above working. 我可以使用数组轻松地做到这一点,但是我想知道如何使上述工作正常进行。 Any idea? 任何想法?
You can create variable names as strings. 您可以将变量名创建为字符串。 You can do this as one line, but I am breaking it up so you can see it easier... 您可以将其作为一行执行,但是我正在将其分解,以便您可以更轻松地看到它。
$var = "fruit";
$var.= rand(1,3);
echo $$var;
You can use double dollar sign to get variable from string: 您可以使用双美元符号从字符串获取变量:
$fruit1 = 'apple';
$fruit2 = 'banana';
$fruit3 = 'orange';
$variable = 'fruit'.mt_rand(1,3);
echo $$variable;
But better is use array: 但是更好的方法是使用数组:
$fruits = array();
$fruits[1] = 'apple';
$fruits[2] = 'banana';
$fruits[3] = 'orange';
echo $fruits[mt_rand(1,3)];
Here is an OOP approach using array_rand(): 这是使用array_rand()的OOP方法:
Class: 类:
class Test {
public $fruits;
public $fruit1;
public $fruit2;
public $fruit3;
public function __set($property, $value)
{
if(property_exists($this, $property)) {
$this->$property = $value;
}
}
public function pickOne()
{
$this->fruits = [];
foreach($this as $key => $value) {
if(!empty($value))
$this->fruits[$key] = $value;
}
return array_rand($this->fruits, 1);
}
}
Then instantiate it, set the property values and echo the result: 然后实例化它,设置属性值并回显结果:
$pickOne = new Test;
$pickOne->fruit1 = 'apple';
$pickOne->fruit2 = 'banana';
$pickOne->fruit3 = 'orange';
echo $pickOne->pickOne();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.