1

how do i compare the with if else statement. in mysql query i can use LIKE % statement.
i want to compare the string result with php. ie: Pro Tan 3mins, Pro Tan 6mins, Pro Tan 9mins

in mysql :

$db->query("SELECT * FROM treat WHERE tanning LIKE 'Pro Tan%'");

in php:

if($tanning == 'Pro Tan') :
  echo 'xxx';
else :
  echo 'zzz';
endif
// output zzz

4 Answers 4

3

There are a variety of different comparison functions you can use, depending on how sophisticated you want to make your comparison. To find specifically a string that starts with "Pro Tan", you could do:

if (strpos($tanning, 'Pro Tan') === 0)
    echo 'xxx';

Note the triple ===, since if strpos returns false, that's not at all the same as returning 0.

Sign up to request clarification or add additional context in comments.

Comments

2

Assuming the result begins with the value, you can use strncmp.

$foo = 'Pro Tan 6mins';
if (strncmp($foo,'Pro Tan', 7) === 0)
  echo 'match';

For case-insensative, you can also use strncasecmp.

Comments

1

You are looking for the strstr() function in PHP, which allows you to search for a string within a string.

if(strstr($tanning, 'Pro Tan')):
  echo 'xxx';
else :
  echo 'zzz';
endif;

2 Comments

Perhaps, but in the SQL example it's not matching ANYWHERE in the string, it's matching specifically at the beginning.
True. My method is more greedy!
0
if(preg_match("/^Pro Tan/",$foo)) {....}

Other answers given will also work, but regular expressions using preg_match() is more flexible and will continue to work with more complex matching.

(some will say that regex is slow, but in this case, since it's just matching a straight string anchored to the start, it's a very efficient query)

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.