8

Need to check if $message length is 7 characters or less, if so, do action A, if not, do action B. Is this correct syntax? I think im doing something wrong?

<?php

if (strlen($message) <= 7) {
    echo $actiona;
} else {
    echo $actionb;
}

?>
Thilina Sampath
  • 3,276
  • 6
  • 37
  • 65
mrpatg
  • 9,741
  • 40
  • 106
  • 166

5 Answers5

20

It's fine. For example, let's run the following:

<?php

$message = "Hello there!";

if (strlen($message) <= 7){
    echo "It is less than or equal to 7 characters.";
} 
else 
{
    echo "It is greater than 7 characters.";
}
?>

It will print: "It is greater than 7 characters."

Evan Fosmark
  • 94,395
  • 33
  • 103
  • 116
  • This is the best code for doing this out of all the ones I've seen recommended on stackoverflow. Source: tested them – Michael d Mar 24 '17 at 14:24
2

You might also want to use the PHP shorthand if/else using the ternary operators (?:).

For example, instead of:

<?php

if (strlen($message) <= 7) {
    echo $actiona;
} else {
    echo $actionb;
}

?>

You can write it as:

<?php echo strlen($message) <= 7 ? $actiona : $actionb; ?>

See How do I use shorthand if / else? for information on the ternary operator.

Marius Balčytis
  • 2,551
  • 19
  • 22
Randell
  • 6,018
  • 5
  • 43
  • 70
1

What error messages are you receiving?

I would check that when you set $message before hand, you haven't misspelt it or used incorrect capitalization (keeping in mind that php is cAsE sensitive).

EvilChookie
  • 543
  • 3
  • 14
  • 31
1

That's OK.

But you should use long php tags (short tags can be disabled ; and quite often are) :

<?php
// ... PHP code
?>

(closing tag being optional, if your file contains only PHP)

Pascal MARTIN
  • 385,748
  • 76
  • 642
  • 654
-1

i found this ISSET "trick" around www , i don't remember where. try first to run the script like this then uncomment the 2nd line $message=.. to write over another string length..

<?php
$actiona="ACTIONA";
$actionb="ACTIONB";

$message="1234567";
//$message="12345678";//try to comment /uncomment these

if (!isset($message{7})) {
    echo $actiona;
} else {
    echo $actionb;
}
?>

AND SURE

<?php
$actiona="ACTIONA";
$actionb="ACTIONB";

$message="1234567";//try to comment /uncomment these
//$message="12345678";


echo !isset($message{7}) ? $actiona : $actionb; 


?>

Good luck! We All Love Php !!!!

Constantin
  • 497
  • 2
  • 13