I have an array of blog_ids and i want to navigate to the previous and next blog_id in that array.
foreach($blog_ids as $blog_id) {
echo $blog_id.'<br />';
}
// output:
id_20200523214047
id_20200523003107
id_20200521125410
id_20200521123813
id_20200514222532
From the current page, i grab the id with $_GET['page'];
echo $_GET['page'];
// ouput
id_20200521125410 (3rd value of array)
How can i now navigate to the previous and next value in that array, from the current id i am?
Previous should be: id_20200523003107 and next should be id_20200521123813
If your array has sequential integer keys, then get the current key and then add or subtract one. If it is already at the first position then return the last one or if it is at the last position return the first one. That may not be the behavior you want, so just change what's after the ?? to whatever you want if next or previous don't exist:
$key = array_search($_GET['page'], $blog_ids);
$prev = $blog_ids[$key-1] ?? end($blog_ids);
$next = $blog_ids[$key+1] ?? reset($blog_ids);
For other arrays just re-index first with:
$blog_ids = array_values($blog_ids);
Also, after re-indexing and searching you could get all 3 with:
list($prev, $curr, $next) = array_slice($blog_ids, $key-1, 3);
PHP has functions for this:
https://www.php.net/manual/en/function.prev.php
https://www.php.net/manual/en/function.next.php
hth
Related
I have an array whick first key starts with one, and I need it like that.
//first iteration of $collections
$collections[1] = $data1;
$collections[2] = $data2;
...
//It does not have to start with zero for my own purposes
So I do the stuff needed like this:
//count($collections) = 56;
$collections = array_map(function($array)use($other_vars){
//more stuff here
//finally return:
return $arr + ['newVariable'=$newVal];
},$collections);
When var_dump($collections); the first key is one, which is fine.
However, when I want to add another variable to the array like these:
//another array starting at one //count($anotherArray) = 56;
$anotherArray[] = ['more'=>'values'];
$collections = array_map(function($arr,$another)use($other_vars){
//more stuff here
//finally return:
return $arr + ['newVariable'=$newVal,'AnotherVar'=>$another['key']];
},$collections,$anotherArray);
Then if I iterate $collections again, it now starts at zero. Why? How can I make it start from 1 instead of zero in the first key?
Any ideas?
So why is the first key changed to zero? How can I keep it to be one?
You can reproduce the problem by executing the following code (for example on php online):
$collections[1]=['data1'=>'value1'];
$collections[2]=['data2'=>'value2'];
$collections[3]=['data3'=>'value3'];
$collections[4]=['data4'=>'value4'];
$another[1]=['AnotherData'=>'AnotherVal1'];
$another[2]=['AnotherData'=>'AnotherVal2'];
$another[3]=['AnotherData'=>'AnotherVal3'];
$another[4]=['AnotherData'=>'AnotherVal4'];
var_dump($collections);
echo '<hr>';
var_dump($another);
echo '<hr>';
$grandcollection=array_map(function($a){
return $a + ['More'=>'datavalues'];
},$collections);
var_dump($grandcollection);
echo '<hr>';
$grandcollection2 = array_map(function($a,$b){
return $a + ['More'=>'datavalues','yetMore'=>$b['AnotherData']];
},$collections,$another);
var_dump($grandcollection2);
Now adding the solution suggested by lerouche
echo '<hr>';
array_unshift($grandcollection2, null);
unset($grandcollection2[0]);
var_dump($grandcollection2);
It now does work as intended
After your $collections has been created, unshift the array with a garbage value and then delete it:
array_unshift($collections, null);
unset($collections[0]);
This will shift everything down by one, moving the first real element to index 1.
I have this array in php code. I want to have that whenever page is being called it should print value of first array index and when next time second value of array index and so on... what modification I could do? for now it´s printing everything when being called single time.
<html>
<?php
$addresses = array('ifcbxespra', 'ifcheqjbmea', 'ifcqiknsa', 'ifcqirtjla', 'ifcwqsrlmn', 'ifclmkmzhz','ifcwdujhgc','ifcihddngh','icffhzudcd','ifchnsqzgs','ifcgssqrhg');
foreach ($addresses as &$value) {
echo $value ;
}
?>
</html>
I'm not sure if I understood what you want. But if you want to print the first array's value when the page loads one time, the second array's value when the page loads another time and so on, you can do this:
<?php
if(!isset($addresses) || empty($addresses)){ //checks if the array is not initialized or if it's empty
$addresses = array('ifcbxespra', 'ifcheqjbmea', 'ifcqiknsa', 'ifcqirtjla', 'ifcwqsrlmn', 'ifclmkmzhz','ifcwdujhgc','ifcihddngh','icffhzudcd','ifchnsqzgs','ifcgssqrhg');
echo $addresses[0]; //print the first value
array_splice($addresses, 0, 1); //removes the first element of the array and reindexes it
}else{
echo $addresses[0]; //print the first value
array_splice($addresses, 0, 1); //removes the first element of the array and reindexes it
}
The logic behinds it is: if the array already exists and is not empty (it has values), print the first value and then remove it, so next time the first value will be the second actual value. When the array is empty, redefine it as to start again.
You can search for more information on array_splice() here.
P.S.: you have to use PHP's $_SESSION to save the array between the pages.
You can use something like $_SESSION and store there the last index.
For example:
$array = array('one', 'two', 'three');
if (!$_SESSION['nextIndex'] || $_SESSION['nextIndex'] >= count($array)) {
$_SESSION['nextIndex'] = 0
}
// print the value
echo $array[$_SESSION['nextIndex']];
// increment the nextIndex
$_SESSION['nextIndex']++;
NOTE: This will only work for the same user. Each page reload will increment the array index. But if you need some cross-user counting, then you have to store the information somewhere on the server, like a DB or even a simple txt file.
Check out this example: http://hibbard.eu/how-to-make-a-simple-visitor-counter-using-php/
Finally I solved this problem with the MySQL. created a column with all code. and then call the script every-time when user press button. In the script first I fetch first raw and print that value, and then, delete that raw. so every-time user will get unique value from the list of code And it is working fine.
This question has been asked a thousand times, but each question I find talks about associative arrays where one can delete (unset) an item by using they key as an identifier. But how do you do this if you have a simple array, and no key-value pairs?
Input code
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
foreach ($bananas as $banana) {
// do stuff
// remove current item
}
In Perl I would work with for and indices instead, but I am not sure that's the (safest?) way to go - even though from what I hear PHP is less strict in these things.
Note that after foreach has run, I expected var_dump($bananas) to return an empty array (or null, but preferably an empty array).
1st method (delete by value comparison):
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
foreach ($bananas as $key=>$banana) {
if($banana=='big_banana')
unset($bananas[$key]);
}
2nd method (delete by key):
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
unset($bananas[0]); //removes the first value
unset($bananas[count($bananas)-1]); //removes the last value
//unset($bananas[n-1]); removes the nth value
Finally if you want to reset the keys after deletion process:
$bananas = array_map('array_values', $bananas);
If you want to empty the array completely:
unset($bananas);
$bananas= array();
it still has the indexes
foreach ($bananas as $key => $banana) {
// do stuff
unset($bananas[$key]);
}
for($i=0; $i<count($bananas); $i++)
{
//doStuff
unset($bananas[$i]);
}
This will delete every element after its use so you will eventually end up with an empty array.
If for some reason you need to reindex after deleting you can use array_values
How about a while loop with array_shift?
while (($item = array_shift($bananas)) !== null)
{
//
}
Your Note: Note that after foreach has run, I expected var_dump($bananas) to return an empty array (or null, but preferably
an empty array).
Simply use unset.
foreach ($bananas as $banana) {
// do stuff
// remove current item
unset($bananas[$key]);
}
print_r($bananas);
Result
Array
(
)
This question is old but I will post my idea using array_slice for new visitors.
while(!empty($bananas)) {
// ... do something with $bananas[0] like
echo $bananas[0].'<br>';
$bananas = array_slice($bananas, 1);
}
This may be a silly question and sorry for any confusing sentences.. I don't know if I can explain this issue well enough to make you understand, but $_SESSION seems unable to be repeated more than once on a page.
session_start();
while (list($a, $b) = each($_SESSION['temp']))
echo "<li>$a - $b</li>";
The above code is ok, but if I have $_SESSION['temp'] on the same page as below, then it doesn't show anything...
session_start();
while (list($a, $b) = each($_SESSION['temp']))
echo "<li>$a - $b</li>";
while (list($c, $d) = each($_SESSION['temp']))
echo "<li>$c - $d</li>"; /* <=== nothing shown :( */
To get the value from the $_SESSION['temp'], I need to give it a new name:
session_start();
$temp = $_SESSION['temp']; /* <== new name */
while (list($a, $b) = each($_SESSION['temp']))
echo "<li>$a - $b</li>";
while (list($c, $d) = each($temp))
echo "<li>$c - $d</li>"; /* <=== now shown :) */
Can you tell me how come $_SESSION['temp'] can't be used twice or more on the same page?
Is there any better way to get a value from $_SESSION['temp']?
Thank you.
http://php.net/manual/en/function.each.php
Return the current key and value pair from an array and advance the array cursor.
After each() has executed, the array cursor will be left on the next element of the array, or past the last element if it hits the end of the array. You have to use reset() if you want to traverse the array again using each.
session_start();
while (list($a, $b) = each($_SESSION['temp']))
echo "<li>$a - $b</li>";
reset($_SESSION);
while (list($c, $d) = each($_SESSION['temp']))
echo "<li>$c - $d</li>";
The other answer is correct, but there is better way:
foreach ($_SESSION['temp'] as $a => $b) {
// do what you wanted with each item
};
// repeat the code here
foreach loop does not require resetting after usage, so it is easier to use (http://php.net/manual/en/control-structures.foreach.php):
When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.
I have a data set from mysql in a multidimensional array.
I am using a pagination script to show 10 per page of that array. I want to know how to append a number to each one like a scoring system. The array is sorted by the way that it will aways be so i want to to add a 1 to the first item, a 2 to the second item and so on.
I dont want to do this in the foreach that i output since this will not translate over to the second page where it would start back at 1.
Any ideas on how to attach a number in desc order to each item in the array so i can access it in the foreach and display it?
Thanks in advance
Use the same math used to find the offset in your pagination query and start counting from there.
fist you need to save the indexes in a $_SESSION variable:
$_SESSION['indexes'] = array();
and for multidimentional:
foreach( $array as $index=>$arrValue) {
echo $index;
foreach($arrValue as $index2=>$value){
echo $index2;
$_SESSION['indexes'][$index][$index2] = $value;
echo $value;
}
}
than you can go through all of the session indexes; where $index is the page or $index2 can be the row
I figured it out by doing some calculations based on which page i was on and the page count that was set and finding the size of the array from the db:
$all_members = get_users_ordered_by_meta('metavalue', 'desc');
$array_count = count($all_members);
$posts_per_page = get_option('posts_per_page');
if ($page > 0) {
$total_posts_avalible = ($posts_per_page * $page);
$usernum = $total_posts_avalible - $posts_per_page;
}
Then i echo the $usernum in the foreach next to the name of the user.
foreach() {
$usernum++;
echo $usernum; echo $user_name;
}