0

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?

0

3 Answers 3

2

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)];
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, it works and is closest to my syntax (the first part). Will accept as answer in few minutes, waiting for SO time limit to pass :)
In case you are using the array there is the array_rand function in PHP.
2

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;

Comments

1

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.