-3

I am beginner in PHP.

I have this array:

$array = array(
    ['name' => 'project 1', 'url' => 'www.name1.com', 'photo' => '1.jpg'],
    ['name' => 'project 2', 'url' => 'www.name2.com', 'photo' => '2.jpg'],
    ['name' => 'project 3', 'url' => 'www.name3.com', 'photo' => '3.jpg'],
    ['name' => 'project 4', 'url' => 'www.name4.com', 'photo' => '4.jpg'],
    ['name' => 'project 5', 'url' => 'www.name5.com', 'photo' => '5.jpg'],
    ['name' => 'project 6', 'url' => 'www.name6.com', 'photo' => '6.jpg'],
)

I need get by function next and previous element from my array (if exist):

$next = next($actualUrl);
$previous = previous($actualUrl);

How can I make it?

trzew
  • 385
  • 1
  • 4
  • 13

3 Answers3

1

this simple code will help you:

<?php

function next_elm ($array, $actualUrl) {
    $i = 0;
    while ( $i < count($array) && $array[$i]["url"] != $actualUrl ) $i++;  
    
   if ($i < (count($array) - 1)) {
       return $array[$i+1];
   } else if ($i == (count($array) - 1)) {
       return $array[0];  // this is depend what you want to return if the url is the last element
   } else {
       return false; // there is no url match
   }
    
}
function prev_elm ($array, $actualUrl) {
    $i = 0;
    while ( $i < count($array) && $array[$i]["url"] != $actualUrl ) $i++;  
    
   if ($i < (count($array)) && $i>0) {
       return $array[$i-1];
   } else if ($i == 0) {
       return $array[count($array) - 1];  // this is depend what you want to return if the url is the first element
   } else {
       return false; // there is no url match
   }
    
}
GNassro
  • 891
  • 1
  • 10
  • 23
0

I prefer to iterate over any array via a foreach loop. if you want anything specific out of it just copy it into a tmp variable. for example:

$tmp_var = null;
foreach($array as $key => $value){
   $tmp_var = $value['name'];
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
0

First find actual url, then use this index to find previous and next items. Also you should add checks if the current item is first or last element to avoid null pointer exception.

$curr = 0;
foreach($array as $value){
    if($value['url'] == 'www.name2.com'){
        break;
    }
    $curr += 1;
}

$previous = $array[$curr-1];
$next = $array[$curr+1];