Home » Php » Check string length in PHP

Check string length in PHP

Posted by: admin April 23, 2020 Leave a comment

Questions:

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.

How to&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";
    }

Answer:

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

Answer:

[0]=> string(141) means that $message is an array, not string, and $message[0] is a string with 141 characters in length.

Answer:

$message is propably not a string at all, but an array. Use $message[0] to access the first element.

Answer:

The xpath() function does not return a string. It returns an array with XML elements (of type SimpleXMLElement), which may be casted to a string.

if (count($message)) {
   if (strlen((string)$message[0]) < 141) {
      echo "There Are No Contests.";
   }
   else if(strlen((string)$message[0]) > 142) {
      echo "There is One Active Contest.";
   }
}

Answer:

An XPath solution is to use:

string-length((//div[@class='contest'])[$k])

where $k should be substituted by a number.

This evaluates to the string length of the $k-th (in document order) div in the XML document that has a class attribute with value ‘contest’.

Answer:

Because $xml->xpath always return an array, and strlen expects a string.