php - Views global counter IF condition is not working?

466

Please can anybody solve my problem. its in drupal 7 views, i dont know why the if condition is not getting satisfied ( if($mycount == 1) ) in the following code.

foreach ($fields as $id => $field){
    if($field->class == "counter")
    {
        $mycount = $field->content;
        echo $mycount;
        echo "<br>";
    }
    if($field->class == "field-logo")
    {
        var_dump($mycount);  // output 
        echo "<br>";
        if($mycount == 1)   // but here 1 == 1 for the first time. see the output.
        {
            echo "worked";  // its not coming here...
        }
    }
}

OUTPUT:

1
string(36) "1"
2
string(36) "2"
3
string(36) "3"
4
string(36) "4"
5
string(36) "5"

Thanks.

581

Answer

Solution:

I suspect that the problem is dumped string size - string(36) - which suggests$mycount content isn't one character but 36 (number "1" and 35 garbage chars). You should try this:

$mycount = trim($field->content);

echo '<pre>as string: ' . var_export($mycount, true)
    . ', is_numeric: ' . var_export(is_numeric($mycount), true)
    . ', as integer: ' . var_export((int) $mycount, true) . '</pre><br />';

You should see something like this on output:

as string: '1', is_numeric: true, as integer: 1
142

Answer

Solution:

I believe Views wrapped your field value in some HTML, so your real output might be<span class="field-content">1</span>, but in browser you only see "1".

In order to avoid getting the result wrapped in HTML you need to change "View result counter" field style settings to "Customize field HTML" and set "- None -" as drop down value.

Now$field->content will return the value without any HTML and$mycount == 1 in your if statement will be working fine.

People are also looking for solutions to the problem: php - See which table a result is in

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.