Php if variable length is equal to

You need to check if the length of $ message is 7 characters or less, if so, do step A, if not, do step B. Is this the correct syntax? I think I'm doing something wrong?

<?php if (strlen($message) <= 7) { echo $actiona; } else { echo $actionb; } ?> 
+5
source share
5 answers

It's good. For example, run the following command:

 <?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."; } ?> 

He will print: "This is more than 7 characters."

+17
source

You can also use the shorthand PHP if / even using ternary operators (? :).

For example, instead of:

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

You can write this as:

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

See How to use if / else shorthand? for information about the ternary operator.

+2
source

What error messages do you get?

I would check that when you put $message in front of the hand, you will not miss it or use the wrong capital letter (bearing in mind that php is sensitive cAsE).

+1
source

This is normal.

But you have to use long php tags (short tags can be disabled and often happen):

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

(closing tag is optional if your file contains only PHP)

+1
source

I found this ISSET "trick" around www, I don’t remember where. try running the script first as follows, then uncomment the second line of $ message = .. to write a line of a different 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 of course

 <?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 !!!!

0
source

All Articles