sriram
sriram

Reputation: 9022

String comparison is not working in php

I'm very new to php. I have a json named json. When I try to do this:

echo $json->status;

I get :

CREATED

I try to compare this result with normal string CREATED like this:

if(strcasecmp("CREATED",$json->status))
{
    print_r("Order created successfuly");
}

but for some reason the if condition is not evaluting to true. Even though I compare CREATED with CREATED!

Not sure where the error is.

Thanks in advance.

Upvotes: 1

Views: 2060

Answers (6)

k102
k102

Reputation: 8079

Look to the manual:

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

so strcasecmp('a','a') is 0, therefore you have to change your code into

if(strcasecmp("CREATED",$json->status) == 0)
{
    print_r("Order created successfuly");
}

Upvotes: 5

Armen Mkrtchyan
Armen Mkrtchyan

Reputation: 921

if (strcasecmp( $json->status, "CREATED") == 0) 
{
...
...

}

Upvotes: 3

Magus
Magus

Reputation: 15104

http://php.net/manual/en/function.strcasecmp.php

Quote from the page :

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

So strcasecmp('CREATED', 'CREATED') returns 0. And 0 is not equals to true. You must do that :

if (strcasecmp("CREATED",$json->status) === 0) {
    print_r("Order created successfuly");
}

Upvotes: 4

OwNAkS
OwNAkS

Reputation: 271

To compare strings, try to do the following :

if($json->status == "CREATED")
{
   echo "Order created successfuly";
}

Upvotes: 0

Bob  Sponge
Bob Sponge

Reputation: 4738

This function return zero if strings are equal

if (strcasecmp("CREATED",$json->status) == 0)

Upvotes: 6

Peon
Peon

Reputation: 8020

Why cant you just use a simpler if statement?

if( $json->status == "CREATED" ) {
    print_r("Order created successfuly");
}

And check for whitespaces at the end or start of the status.

Upvotes: 0

Related Questions