user2620804
user2620804

Reputation: 133

Compare single array value

How can I do a comparison when my array returns value with index.

Returned value is Array ( [isMember] => 0 ) and I want do to a comparison on the value only

   if ($memberStatus == 0)
   {
     print_r($memberStatus);
   }

Upvotes: 0

Views: 1098

Answers (5)

Andrej Buday
Andrej Buday

Reputation: 609

I am not sure which type of array you need to compare because there are generally 2 different types of them:

Indexed - You pick numerical index which do you want to compare

 $array = array("admin", "moderator", "user");

 if ($array[0] == "user") {
    // CODE
 }

Associative - You pick the string key which do you want to compare

 $array = array( "id1" => "member", "id2" => "not member","id3" => "user");

 if ($array["id2"] == "not member") {
     // CODE
 }

Upvotes: 0

Ahmer Saeed
Ahmer Saeed

Reputation: 596

Explanation

Index Array's value can be access by using corresponding index value where as an Associative Array's value can be access by using corresponding key along with array name and in between square brackets that is

arrayName["index-value"]

or

arrayName["key-name"].

You may refer to the following code.

Code

     //For Associative Array
     
     $arrayOne = array(
         'keyone' => 'a',
         'keytwo' => 'b',
         'keythird' => 'c'
     );

     if ($arrayOne['keyone'] == 'a') {
         print_r($arrayOne['keyone']);
         //output a
     }

OR

   //For Index Array

     $arrayOne = array('a', 'b', 'c');

     if ($arrayOne[0] == 'a') {
        print_r($arrayOne[0]);
       //output a
     }

Upvotes: 2

Solrac
Solrac

Reputation: 931

Are you looking for a key inside an array? Then you need:

echo array_key_exists(9, [1=>'nope',2=>'nope',3=>'nope',9=>'yah']) ? 'Yes it does' : 'it doesn\'t';

Otherwise you are looking for:

echo in_array("my value", ["my value", "a wrong value", "another wrong one"]) ? 'yush' : 'naaaaah';

Either way you can use both in a if statement rather than a thernary operator.

Upvotes: 0

Tarwin Stroh-Spijer
Tarwin Stroh-Spijer

Reputation: 353

I think what you are looking for is:

$myArray = array(
  'isMember' => 0
);

if ( $myArray['isMember'] == 0 ) {
  print_r($myArray['isMember']);
}

Upvotes: 0

Manuel Mannhardt
Manuel Mannhardt

Reputation: 2201

If you have an array like this:

$data = [ 'isMember' => 0, 'data1' => 1, 'data2' => 2 /* ... */ ];

You can access single elements by using the name of the array and write the key in square brackets:

// change isMember to whatever key-value pair you need
$memberStatus = $data['isMember'];

if ($memberStatus === 0)
{
    print 'user is a member';
}

else
{
    print 'user it not a member';
}

Upvotes: 1

Related Questions