2

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!

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Maybe also mention the ability to assign dynamic variable names, which is essentially what is the OP after, not an array (not that it's more efficent), with ${$name}...
this doesn't work, when I do var_dump($array) outside the while loop it gives me only ONE last $data string...
@Wordpressor: You might be doing something wrong anywhere please check you code again.
2

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.

2 Comments

While this does work and answers the OP's exact question, I'm having trouble imagining a use case where this pattern is preferable to the alternative solution proposed by @Shakti Singh.
@Schwartzie, agreed, which is why I included the bit about using an array. They're really just different semantics for the very same functionality, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.