Jump to content

if ... else random


manalnor

Recommended Posts

Hello dear friends,

 

Let say we have files

 

red.php

orange.php

blue.php

yellow.php

 

here is the main question

 

if ($any == 1)
{
require_once("red.php");
} else {
xxxxxxxxxxxxxxxxxxxxxxxx
}

 

how to make it else ( show random files )

i mean instead of xxxxxxxxxxxxx it will pick up any file in random way.

 

how to write this !

thanks in advance

Link to comment
Share on other sites

$colors = Array('red.php', 'blue.php', 'orange.php', 'yellow.php');
$max = count($colors) - 1;
$rand = rand(0, $max);
echo "Random Color: {$colors[$rand]}";

 

Careful on Jay's method - you could grab any php file.

Link to comment
Share on other sites

True, I did think that myself, but it was assuming that all the files are in a separate folder with the .php extension. If they aren't then go with a normal array method or give your files a certain suffix such as

red.color.php

then search for *.color.php instead of just *.php

Link to comment
Share on other sites

thanks so much for both ways and i understood that Jay method will take any *.php file with it but will be fine is the files in /templates dir.

 

 

one last question, is that possible to be in that way

 

if ($wpic == red) {
require_once("red.php");
} else if($wpic == blue) {
require_once("blue.php");
} else if($wpic == yellow) {
require_once("yello.php");
} else {
xxxxxxx ddubs code for random xxxxxxxx
}

 

 

i mean is it possible to use chain of (else if) i mean many times.

Link to comment
Share on other sites

Yea thats fine, or you can research "switch"

 

switch($wpic) {
  case $wpic == 'red' :
    require_once("red.php");
    break;
  case $wpic == 'blue' :
    require_once("blue.php");
    break;
...etc
  default :
  //insert random code here...
}

Link to comment
Share on other sites

i mean is it possible to use chain of (else if) i mean many times.

 

Yes, but in this case it is inefficient

$colors = array('red', 'blue', 'yellow');

if (in_array(strtolower($wpic), $colors))
{
    $require_file = strtolower($wpic) . '.php';
}
else
{
    $require_file = $colors[array_rand($colors)] . '.php';
}

require_once($require_file);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.