Obmerk Kronen
Obmerk Kronen

Reputation: 15949

PHP array of numbers with range() and foreach loop

I have a really strange problem with range(); According to docs :

Create an array containing a range of elements

But when I do :

foreach (range(900,950,1) as $art_id){
    //ob_start();
    //do stuff
    //do a lot more stuff
    echo $art_id;
    //ob_get_clean(); }

or even

$arts_id = range (900, 920);
 foreach ($arts_id as $art_id){
        //ob_start();
        //do stuff
        //do a lot more stuff
        echo $art_id;
        //ob_get_clean(); }

The output is strangly repeating itself in a series like

"900,900,901,900,901,902,900,901,9002,903,900..."

meaning it is comming back to the first ID after each loop.

(1st iteration -> 900
2nd iteration -> 900,901
3rd iteration -> 900,901,902
...)

When I just put a manual array it works perfectly in order and no duplicates :

$arts_id = array(900,901,902,903,904,905,906,907,908,909,910...);

What Am I doing wrong (again ?? )

EDIT I

here is the whole script :

http://pastebin.com/ZHm3ub6n

It is actually a slightly modified version of the slashdot scraping example included in the simplehtmldom script . Nothing special.

It is executed inside WP but OUTSIDE the loop ..

Upvotes: 2

Views: 6721

Answers (1)

TheWolfNL
TheWolfNL

Reputation: 1283

It must be in the rest of your code, because this works fine. please share more of the script.

It looks like the foreach is nested within a similair foreach,

 $arts_id = range (900, 920);
 foreach ($arts_id as $art_id){
    foreach (range (900,$art_id) as $art_id2){
        echo $art_id2."<br/>";
    }
 }

This produces an output you've described

EDIT

Personally i'd add the the function scraping_slashdot a reset of the variable $ret just in case.

for example: $ret = array();

Currently the echo of $output is within the loop, which creates an output like the following:

Article 1
Article 1, Article 2
Article 1, Article 2, Article 3
etc.

place echo $output outside the loop, or $ouptut = ''; inside the loop.

Upvotes: 3

Related Questions