FAFAFOHI
FAFAFOHI

Reputation: 909

Check string length in 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.

Upvotes: 39

Views: 147728

Answers (6)

Capitaine
Capitaine

Reputation: 2005

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

Upvotes: 1

Emmerman
Emmerman

Reputation: 2343

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

Upvotes: 4

nicola
nicola

Reputation: 2211

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

Upvotes: 87

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243599

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

Upvotes: 1

ZeissS
ZeissS

Reputation: 12135

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

Upvotes: 3

Poelinca Dorin
Poelinca Dorin

Reputation: 9715

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

Upvotes: 12

Related Questions