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/… Commented 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 } Commented Sep 3, 2012 at 10:40
  • $variable == $one does this not work for you. Array can be compared as variables Commented Sep 3, 2012 at 10:41
  • Do you have the ability to place indexes of the array values: 'one' => $one, 'two' => $two... Commented 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. Commented 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
    }   
?>
Sign up to request clarification or add additional context in comments.

2 Comments

$three = array (1,2,3); $variables[] = $three;. That will execute the // do stuff twice.
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.
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 Comments

Why the downvote? Is this not a viable alternative to getting the name of a variable?
Thank you, this was the solution I was looking for.
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)
        {

        }
    } 

Comments

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.

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.