Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check string length in PHP

Tags:

string

php

I have a string that is 141 characters in length. Using the following code I have an if statement to return a message if the string is greater or less than 140.

libxml_use_internal_errors(TRUE); $dom = new DOMDocument(); $dom->loadHTMLFile($source); $xml = simplexml_import_dom($dom); libxml_use_internal_errors(FALSE); $message = $xml->xpath("//div[@class='contest']");  if (strlen($message) < 141) {    echo "There Are No Contests."; } elseif(strlen($message) > 142) {    echo "There is One Active Contest."; } 

I used var_dump on $message and it shows the string is [0]=> string(141). Here is my problem: When I change the numbers for the if statement to <130 and >131, it still returns the first message, although the string is greater than 131.

No matter what number I use less than 141 I always get "There Are No Contests." returned to me.

like image 603
FAFAFOHI Avatar asked Apr 06 '11 07:04

FAFAFOHI


People also ask

How do you find the length of a string in PHP?

The strlen() function returns the length of a string.

How do I count characters in PHP?

The strlen() is a built-in function in PHP which returns the length of a given string. It takes a string as a parameter and returns its length. It calculates the length of the string including all the whitespaces and special characters.

What is the use of strpos () function in PHP?

strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string or a string inside another string. The function returns an integer value which is the index of the first occurrence of the string.


2 Answers

Try the common syntax instead:

if (strlen($message)<140) {     echo "less than 140"; } else     if (strlen($message)>140) {         echo "more than 140";     }     else {         echo "exactly 140";     } 
like image 182
nicola Avatar answered Sep 21 '22 12:09

nicola


[0]=> string(141) means $message is an array so you should do strlen($message[0]) < 141 ...

like image 33
Poelinca Dorin Avatar answered Sep 18 '22 12:09

Poelinca Dorin