PHP get previous array element knowing current array key
One option:
To set the internal pointer to a certain position, you have to forward it (using key
and next
, maybe do a reset
before to make sure you start from the beginning of the array):
while(key($array) !== $key) next($array);
Then you can use prev()
:
$prev_val = prev($array);
// and to get the key
$prev_key = key($array);
Depending on what you are going to do with the array afterwards, you might want to reset
the internal pointer.
If the key does not exist in the array, you have an infinite loop, but this could be solved with:
while(key($array) !== null && key($array) !== $key)
of course prev
would not give you the right value anymore but I assume the key you are searching for will be in the array anyway.
Getting the previous and next keys/values in array from current position (PHP)
You can use array functions for that
$NextKey = next($BookIndex); // next key of array
$PreviousKey = prev($BookIndex); // previous key of array
$CurrentKey = current($BookIndex); // current key of array
pointing to specific position
$CurrentKey = '2';
while (key($BookIndex) !== $CurrentKey) next($BookIndex);
Get previous array key in associative array
<?php
$arr = array(
0 => array('first_name' => 'Ace', 'last_name' => 'Jones'),
1 => array('first_name' => 'Aron', 'last_name' => 'Jones'),
2 => array('first_name' => 'Ben', 'last_name' => 'Jones'),
3 => array('first_name' => 'Billy', 'last_name' => 'Jones'),
4 => array('first_name' => 'Barney', 'last_name' => 'Jones'),
5 => array('first_name' => 'Con', 'last_name' => 'Jones'),
6 => array('first_name' => 'Dan', 'last_name' => 'Jones'),
7 => array('first_name' => 'Earl', 'last_name' => 'Jones'),
8 => array('first_name' => 'East', 'last_name' => 'Jones'),
9 => array('first_name' => 'Fez', 'last_name' => 'Jones')
);
sort($arr); // ensure correct order
$html = '';
foreach($arr as $k => $v) {
if(substr($v['first_name'], 0, 1) != $previous) {
$html .= '<tr><td>' . substr($v['first_name'], 0, 1) . '</td>';
} else {
$html .= '<tr><td> </td>';
}
$html .= '<td>' . $v['first_name'] . '</td>';
$html .= '<td>' . $v['last_name'] . '</td></tr>';
$previous = substr($v['first_name'], 0, 1);
}
?>
<table rules="all" style="border: 1px solid blue;" cellspacing="2" cellpadding="2">
<tr>
<td>Label</td>
<td>First Name</td>
<td>Last Name</td>
</tr>
<?php echo $html; ?>
</table>
The general idea is that you want to store the previous result in a variable before you compare what the current items and what the previous item is. The $previous
variable store the previous item which is checked against the current item before $previous
is updated. Remember that PHP executes line by line. If the first letter of the previous result does not equal the first letter of the previous item, then let's add it. Otherwise, add a non-breaking whitespace character to preserve the table cell's visibility.
This seems to be exactly what you want to do. There are ways you can clean this up but it's exactly as you want it. See the code
Get value of previous array key
Your current value from $array["second"]
is not an array and prev takes an array as a parameter.
You have to move the internal pointer of the $array
and then get the previous value.
$array = array('first'=>'111', 'second'=>'222', 'third'=>'333');
while (key($array) !== "second") next($array);
var_dump(prev($array));
PHP - fast way to get previous array elements before specific key
You can iterate through and push values to a newArray
until you hit the key you are searching for:
$Key = 256;
$array = array(
"125" => array(571, 570),
"284" => array(567, 566),
"256" => array(562, 560),
"110" => array(565, 563),
);
$newArray = [];
foreach($array as $key => $value)
{
if($key == $Key) break;
$newArray[$key] = $value;
}
print_r ($newArray);
/*
=> Array (
[125] => Array ( [0] => 571 [1] => 570 )
[284] => Array ( [0] => 567 [1] => 566 )
)
*/
php check if previous array key value is the same as current array thats being checked
This seems to work
<?php
$results = array(
array('value' => 100, 'ID' => 333, 'sec' => 200),
array('value' => 200, 'ID' => 333, 'sec' => 300),
array('value' => 300, 'ID' => 555, 'sec' => 400),
array('value' => 400, 'ID' => 555, 'sec' => 500),
array('value' => 500, 'ID' => 333, 'sec' => 600)
);
$display = array();
foreach($results as $id => $value) {
if($id>0 AND $display[count($display)-1]['ID'] == $value['ID']) {
$display[count($display)-1]['sec'] = $value['sec'];
} else {
$display[] = $value;
}
}
print_r($display);
RESULTS
Array
(
[0] => Array
(
[value] => 100
[ID] => 333
[sec] => 300
)
[1] => Array
(
[value] => 300
[ID] => 555
[sec] => 500
)
[2] => Array
(
[value] => 500
[ID] => 333
[sec] => 600
)
)
PHP - Get key name of array value
If you have a value and want to find the key, use array_search()
like this:
$arr = array ('first' => 'a', 'second' => 'b', );
$key = array_search ('a', $arr);
$key
will now contain the key for value 'a'
(that is, 'first'
).
How to get next key in an array from given key in php?
Try this out
function get_next_key_array($array,$key){
$keys = array_keys($array);
$position = array_search($key, $keys);
if (isset($keys[$position + 1])) {
$nextKey = $keys[$position + 1];
}
return $nextKey;
}
Given a PHP associative array and a current key, calculate the next and previous elements (with looping)
$key = 'a';
$keys = array_keys($pages);
$cur = array_search($key, $keys);
$next = $keys[($cur + 1) % count($keys)];
$prev = $keys[($cur - 1 + count($keys)) % count($keys)];
echo $pages[$prev] ."\n";
echo $pages[$next] ."\n";
result
/pages/something-else
/pages/another
Related Topics
Adding Multiple Items to Woocommerce Cart at Once
How to Check If Variable Is Array... or Something Array-Like
Reaching 100% Code Coverage with PHPunit
Detect In-App Browser (Webview) with PHP/Javascript
How to Set Session Timeout in Laravel
Require_Once :Failed to Open Stream: No Such File or Directory
Phpmysql Error - #1273 - #1273 - Unknown Collation: 'Utf8Mb4_General_Ci'
PHP Datetime Createfromformat Functionality
Read the Session Data from Session Storage File
Returning First X Items from Array
What's the Difference Between Is_Null($Var) and ($Var === Null)
Try Catch Cannot Work with Require_Once in PHP
When Do I Use PHP_Eol Instead of \N and Vice-Versa? Ajax/Jquery Client Problem
Using If(!Empty) with Multiple Variables Not in an Array
What Is a Good Method to Sanitize the Whole $_Post Array in PHP
Assets Not Referencing to Public Folder (Laravel)
Can Closing the Browser Terminate the PHP Script on the Server