here is my sample
Array
(
[0] => stdClass Object
(
[id] => 4
)
[1] => stdClass Object
(
[id] => 3
)
[2] => stdClass Object
(
[id] => 2
)
[3] => stdClass Object
(
[id] => 1
)
}
- I am getting an id = 3 on my page , how can I get previous and next id based on id I am getting on my page using the above array
rpkamp
2
function getPreviousAndNext($rows, $current): array
{
$ids = array_map(
static function($row) {
return $row->id;
},
$rows
);
$currentIndex = array_search($current, $ids);
if (false === $currentIndex) {
// current not found in rows, unable to determine
// previous and next
return [null, null];
}
return [
$ids[$currentIndex - 1] ?? null,
$ids[$currentIndex + 1] ?? null,
];
}
See https://repl.it/repls/PointlessImpeccableType for a working example of how to use it 
Dont reinvent the wheel, Ramon 
$ids = array_column($rows,'id');
rpkamp
4
I though about that, but that only works on assoc arrays, no? The OP has an array of objects with public properties.
Edit: turns out it works on arrays with objects that have public properties as well. Never knew that. So yes. That would be shorter 
system
Closed
6
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.