Reputation: 8684
Given the 3 variables below, each ending in a number. 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.
<?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?
Upvotes: 0
Views: 452
Reputation: 1139
Here is an OOP approach using array_rand():
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();
Upvotes: 1
Reputation: 3354
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)];
Upvotes: 2
Reputation: 4334
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;
Upvotes: 2