I am currently doing a little script (and I am rather beginner), I would like to know how to return to the result number one of a for loop after the table containing the results have been traveled?
here's the code:
$currenttPostId = get_the_ID();
$theCategory = get_the_terms(get_the_ID(),'category');
$prevNext = array();
if (!empty($search_args)) {
$search_args['posts_per_page'] = -1;
for ($i = 0; $i < count($search_results); $i++) {
if ( $search_results[$i]->ID == $currenttPostId ) {
$prevNext[] = $search_results[$i - 1];
$prevNext[] = $search_results[$i + 1];
}
}
}
I am currently doing a little script (and I am rather beginner), I would like to know how to return to the result number one of a for loop after the table containing the results have been traveled?
here's the code:
$currenttPostId = get_the_ID();
$theCategory = get_the_terms(get_the_ID(),'category');
$prevNext = array();
if (!empty($search_args)) {
$search_args['posts_per_page'] = -1;
for ($i = 0; $i < count($search_results); $i++) {
if ( $search_results[$i]->ID == $currenttPostId ) {
$prevNext[] = $search_results[$i - 1];
$prevNext[] = $search_results[$i + 1];
}
}
}
Share
Improve this question
edited Feb 14, 2019 at 11:47
Krzysiek Dróżdż
25.6k9 gold badges53 silver badges74 bronze badges
asked Feb 14, 2019 at 11:37
Frenchy_WPFrenchy_WP
191 silver badge6 bronze badges
2
- 1 What exactly do you mean by "return to the result number one of a for loop after the table containing the results have been traveled"? What do you want to achieve? – Krzysiek Dróżdż Commented Feb 14, 2019 at 11:46
- Let's say that I have a query that shows me a page of 12 articles, when we click on one of these articles, it brings us back to the single page, on this single page, I created a pagination brings up to the twelfth article and what I would like is that the twelfth article brings me back to the first one when I click on next – Frenchy_WP Commented Feb 14, 2019 at 11:55
1 Answer
Reset to default 0You can instantly access any position in an array by specifying the index.
i.e. to get the first element of the $search_results array:
$first_result = $search_results[0];
Note if you're not used to working with arrays, they are "0" indexed in most languages, which means the first element's index is 0, the second is 1, etc.
This is what your loop is basically doing as well. Each time it accesses a different number directly, $search_results[$i] is just putting the value of $i in the same spot as I had the 0 above.
You can also change the value of $i in your loop if you want to start the loop over, for instance. Adding the line:
$i = 0;
...would send you back to the beginning. However I would not recommend you work with the index of a loop until you are quite comfortable with them.