Jump to content

How to compare a value of variable against values of variables in an array using PHP?

- - - - -

  • Please log in to reply
4 replies to this topic

#1
Dorgon

Dorgon

    Newbie

  • Members
  • PipPip
  • 24 posts
I have a stupid question.

I have a variable $var

And the content of this variable is even to one of the other variables content; $friendofvar and $friendofvar2

So what I want is that if the content of $var is even to one of the other variables, it should load an unique function.
Like, if the content of $var = $friendofvar: load function "they are friends"
or of the content of $var = $friendofvar2: load function "they are friends too"

The list of variables that I compare with the $var is ganna be kinda big, like 20-25 variables.
Every variable has it own unique function
How can I solve this?

Thanks in advance!

Greetings,

Dorgon

#2
RHochstenbach

RHochstenbach

    Learning Programmer

  • Members
  • PipPipPip
  • 56 posts
You can just do the following:


foreach($var as $contents) {

   if($contents == $friendofvar) {

      echo "they are friends";

    } elseif($contents == $friendofvar2) {

      echo "they are friends too";

   }

}



#3
Dorgon

Dorgon

    Newbie

  • Members
  • PipPip
  • 24 posts
Well, that is not realy what I ment.

Now you only work with 2 variabales, so lets say I want to compare 25 variabels to that one, than u get this:


foreach($var as $contents) {

   if($contents == $friendofvar) {

      echo "they are friends";

    } elseif($contents == $friendofvar2) {

      echo "they are friends too";

    } elseif($contents == $friendofvar3) {

      echo "they are more than friends :0";

    } elseif($contents == $friendofvar4) {

      echo "stop it! it is getting too dirty for this forum!!!";


....

...

   }

}  


you get the idea, this is dirty programming right?

#4
Orjan

Orjan

    Writes binary right handed and hex left handed

  • Moderators
  • 3,299 posts
  • Location:Karlstad, Sweden
  • Programming Language:C, Java, C++, C#, PHP, JavaScript, Pascal
  • Learning:Java, C#
Yes. sort of. but it works. The best way would of course be to use an array $friendofvar[].
__________________________________________
I study Information Systems at Karlstad University when I'm not on CodeCall

#5
leeyo

leeyo

    Newbie

  • Members
  • PipPip
  • 12 posts
foreach($var as $content)
{
if(in_array($content,$friendVar))
{
$content();
}
}




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users