Jump to content

[SOLVED] switch problem ..


php new bie

Recommended Posts

This code makes me crazy  ???

 

why the numbers won't work properly when matched !!

 

 

 

<?php
$rand = rand(1,5);
$num = array(0,1,2,3,4,5);
$match = "" ;
echo "<PRE>";

print_r($num);

echo "</PRE>";

echo "rand = ". $rand . "<br />";


switch ($match){
     
        case ($rand == $num['1'] ):
        $match = "PRE";                
        echo $match;
        break;
        case ($rand == $num['2']):
        $match = "1st";
        echo $match;
        break;
          case ($rand == $num['3'] ):
        $match = "2nd";
        echo $match;
        break;
        case ($rand == $num['4']):
       $match = "3rd";
        echo $match;
        break;
        case ($rand == $num['5']):
        $match = "4th";
        echo $match;
       break;
       default :
        $match = "NAH!";
        break; 
              
}



?>

Link to comment
https://forums.phpfreaks.com/topic/158775-solved-switch-problem/
Share on other sites

Maybe something like:

 

$rand = rand(1,5);
echo "rand = ". $rand . "
";

switch ($match){
     
case 0:
   $match = "PRE";        
   echo $match; 
   break;  
case 1:
   $match = "1st";
   echo $match; 
   break;  
case 2:
   $match = "2nd";
   echo $match; 
   break;  
case 3:
   $match = "3rd";
   echo $match; 
   break;  
case 4:
   $match = "4th";
   echo $match; 
   break;  
default :
   $match = "NAH!"; 
   break;  
         
}

?>

It's not a logical error. What are you trying to do? Switch goes like this:

 

<?php

switch ($value) {
     case $value1:
           // do something
           break;
     case $value2:
           // do something
           break;
     .
     .
     .
}

 

$value1 and $value2 are supposed to be values that $value (the one inside the switch) can be. So if you put:

 

case ($rand == $num['1'] ):

 

Then you're checking if $match is the value of $rand == $num['1'], which is a boolean value and $match is a string.

 

Also, you don't really need a switch for this. You can use array_search and append the proper suffix.

Maq,

 

I used Nightslyr's suggestion and it works like a knife in butter xD

 

thank you again and thanks to all.

 

by the way this is a Demo not the real script because the real one is Messy and I need this function in the code so I write this simple one to be more easier to all to understand the problem exactly :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.