user3522742
user3522742

Reputation: 51

count within foreach doesn't work in my case

foreach ($dom->find('.post h1 a') as $checkIfResultTrue2) {
    $totalSearchResult = $checkIfResultTrue2->href;

        if(count($totalSearchResult) > 1){
            echo "more than 1";
        }
     }

why this didn't print more than 1? I tried .length but realised that is JS. I tried sizeof and count, no luck. When I echo $totalSearchResult, there are more than 1 links there.. hmm, what is the problem?

Upvotes: 0

Views: 76

Answers (2)

RNK
RNK

Reputation: 5792

You are overwriting one variable. Take that variable as array, and add every elements in that array. It should be,

$totalSearchResult=array();

foreach ($dom->find('.post h1 a') as $checkIfResultTrue2) {
array_push($totalSearchResult, $checkIfResultTrue2->href);        <---

    if(count($totalSearchResult) > 1){
        echo "more than 1";
    }
 }

Upvotes: 2

marian0
marian0

Reputation: 3327

Because you overwrite value of $totalSearchResult as string. If $totalSearchResult is an array, you should write to it as follow:

$totalSearchResult = array();
foreach ($dom->find('.post h1 a') as $checkIfResultTrue2) {
    $totalSearchResult[] = $checkIfResultTrue2->href;
    ...
}

Upvotes: 3

Related Questions