Wonka
Wonka

Reputation: 8684

PHP - Echo variable with a random number?

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

Answers (3)

Ravi Gehlot
Ravi Gehlot

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

Mohammad Hamedani
Mohammad Hamedani

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

kainaw
kainaw

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

Related Questions