How to return from a function multiple variables Wordpress?

For example, there is a category with posts.
I need the function to get the title for each post in this category.

$test_query_args = array(
 'post_type' => 'question', 
 'posts_per_page' => 4, 
);

 $test_json_query = get_posts( $test_query_args );

 foreach ( $test_json_query as $post ) : 
 setup_postdata( $post );

get_the_title();
endforeach;
 wp_reset_postdata(); 

 return rest_ensure_response( $end_variable );

you must not echo, namely, get all the title of this series in one variable $end_variable - how to do it?
August 23rd 19 at 10:58
2 answers
August 23rd 19 at 11:00
Solution
as said to return the array.
$test_query_args = array(
 'post_type' => 'question', 
 'posts_per_page' => 4, 
);

$end_variable = array();
 $test_json_query = get_posts( $test_query_args );

 foreach ( $test_json_query as $post ) : 
 setup_postdata( $post );

 $end_variable[] = get_the_title();
endforeach;
 wp_reset_postdata(); 

 return rest_ensure_response( $end_variable );


but IMHO in your case much faster to run in the database directly than to create a new instance of the WP_Query class
I decided my goal by $end_variable .= get_the_title(); what does $end_variable[] ? - Beaulah.Ernser commented on August 23rd 19 at 11:03
adds an element to the array and your $end_variable .= appends a string at the same time you will love in the logs NOTIS for $end_variable you have not declared, or you do not indicated - Whitney_Dicken commented on August 23rd 19 at 11:06
: I used the variable from your example (I have in the end appeared similar); thanks, now is clear! - Beaulah.Ernser commented on August 23rd 19 at 11:09
: Please, but direct to ask the database 4 of title from the records that WHERE post_type = question it will be much faster - Whitney_Dicken commented on August 23rd 19 at 11:12
a function to generate response in json, queries can be many. Directly in the database - how? - Beaulah.Ernser commented on August 23rd 19 at 11:15
August 23rd 19 at 11:02
So the title and so you have returned, just not written anywhere, you have $var = get_the_title()

Find more questions by tags PHPWordPress