mrpatg
mrpatg

Reputation: 10117

php check if variable length equals a value

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;
}

?>

Upvotes: 8

Views: 69083

Answers (4)

Randell
Randell

Reputation: 6170

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.

Upvotes: 2

Pascal MARTIN
Pascal MARTIN

Reputation: 400972

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)

Upvotes: 1

EvilChookie
EvilChookie

Reputation: 573

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).

Upvotes: 1

Evan Fosmark
Evan Fosmark

Reputation: 101671

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."

Upvotes: 21

Related Questions