39

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
FAFAFOHI
  • 909
  • 2
  • 11
  • 15

6 Answers6

87

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";
    }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
nicola
  • 2,141
  • 1
  • 19
  • 19
12

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

Poelinca Dorin
  • 9,577
  • 2
  • 39
  • 43
4

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Emmerman
  • 2,371
  • 15
  • 9
3

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

ZeissS
  • 11,867
  • 4
  • 35
  • 50
1

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Capitaine
  • 1,923
  • 6
  • 27
  • 46
1

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

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431