1

In the below code, how do I check if $variable equals "$one".

<?php  
    $one = array (1,2,3);
    $two = array (4,5,6);

    $variables = array ($one, $two);

    foreach ($variables as $variable){
        //check if the $variable is equal to "$one"
            //do stuff that is specific for array $one
    }   
?>
7
  • Check stackoverflow.com/questions/255312/…
    – napolux
    Sep 3, 2012 at 10:40
  • Please clarify your question. Do you want to just check if $variable is equal to $one or no? if($variable == $one) { //Do things } Sep 3, 2012 at 10:40
  • $variable == $one does this not work for you. Array can be compared as variables Sep 3, 2012 at 10:41
  • Do you have the ability to place indexes of the array values: 'one' => $one, 'two' => $two...
    – Rolice
    Sep 3, 2012 at 10:41
  • 1
    This question doesn't make a whole lot of sense. Please clarify what you are trying to do exactly and why.
    – deceze
    Sep 3, 2012 at 10:42

4 Answers 4

4

For more information visit this

<?php  
    $one = array (1,2,3);
    $two = array (4,5,6);

    $variables = array ($one, $two);

    foreach ($variables as $variable){
        //check if the $variable is equal to "$one"
           if($variable === $one)
            //do stuff
    }   
?>
2
  • $three = array (1,2,3); $variables[] = $three;. That will execute the // do stuff twice. Sep 3, 2012 at 10:46
  • 2
    if this is really what the OP wants, the question should be closed because it's not a real question asking how to do an IF block.
    – Gordon
    Sep 3, 2012 at 10:47
1

Simply put, you can't. You can add a key to the values though:

<?php  
$one = array (1,2,3);
$two = array (4,5,6);

$variables = array ( 'one' => $one, 'two' => $two);

foreach ($variables as $key => $variable){
    //check if the $variable is equal to "$one"
    if( $key === 'one' ) {
        //do stuff that is specific for array $one
    }
}   
2
  • Why the downvote? Is this not a viable alternative to getting the name of a variable? Sep 3, 2012 at 10:45
  • Thank you, this was the solution I was looking for.
    – Nikola
    Sep 3, 2012 at 11:23
1
  foreach ($variables as $variable){
        if($variable == $one)//TRUE if $a and $b have the same key/value pairs.
        {

        }
    } 

And if you want to check for order and types as well you can do as follow:

  foreach ($variables as $variable){
        if($variable === $one)
        {

        }
    } 
1

You can check with

if($variable===$one)

You are taking multi dimensional array. Keep in mind and you need to check with "===", not with "==" because its not an variable or even a string.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.