Wordpressor
Wordpressor

Reputation: 7543

PHP while loop

I have this very simple Wordpress while loop:

$loop = new WP_Query( args ) );

while ( $loop->have_posts() ) : $loop->the_post(); 
   $data = grab_something( args );
   echo $data;
   echo "<br/";   
endwhile; 

This gives me something like:

datastring1
datastring2
anotherdata
somethingelse
and else
and so forth
(...)

I want to save these values from while loop as an array or variables, eg.

$data1 = "datastring1";
$data2 = "datastring2";
$data3 = "anotherdata";
(...)

How to? :)

Thanks!

Upvotes: 2

Views: 4898

Answers (2)

Henry Merriam
Henry Merriam

Reputation: 824

Use a counter $i to keep track of the number, and then you can save the results either as an array or as a set of variables.

$loop = new WP_Query( args ) );

$i = 0;
while ( $loop->have_posts() ) : $loop->the_post(); 
   $data = grab_something( args );
   $i++;
   $array[] = $data; // Saves into an array.
   ${"data".$i} = $data; // Saves into variables.
endwhile; 

You only need to use the $i counter if you use the second method. If you save into an array with the above syntax, the indexes will be generated automatically.

Upvotes: 2

Shakti Singh
Shakti Singh

Reputation: 86346

You can save in array easily

    $array=array();
    while ( $loop->have_posts() ) : $loop->the_post(); 
        $data = grab_something( args );
        $array[]=$data;

    endwhile; 

print_r($data);

$array will store data from index 0 to the number of elements while loop iterate

Upvotes: 3

Related Questions