Quantcast
Channel: AuthorCode » Array in PHP
Viewing all articles
Browse latest Browse all 5

next() and prev() functions in an array of PHP

$
0
0

You can get the index of a new element added to an array with the help of next() function. next() and prev() functions enable us to navigate through arrays by moving the pointer to the next or previous element in the array.

See the following example of codes:

  1. $Capitals[3] = "New Delhi";
  2. $Capitals[7] = "Washington";
  3. $Capitals[1] = "Landon";
  4. $Capitals[5] = "Paris";
  5. $Capitals[11] = "Moscow";
  6. $Capitals[] = "Tokyo";

And now use the next() function and then use key() function to get the current index:

  1. next($Capitals);
  2. $current_index = key($Capitals);
  3. echo ($current_index);

the output will be 7, and now if you call next() function three times:

  1. next($Capitals);
  2. next($Capitals);
  3. next($Capitals);
  4. $current_index = key($Capitals);
  5. $current_item = Current($Capitals);
  6. echo ($current_index);
  7. echo ($current_item );

The value 5 and “Paris” are displayed.
And now use prev() function after three next() function:

  1. next($Capitals);
  2. next($Capitals);
  3. next($Capitals);
  4. prev($Capitals);
  5. $current_index = key($Capitals);
  6. $current_item = Current($Capitals);
  7. echo ($current_index);
  8. echo ($current_item );

The value 1 and “Landon” are displayed, because you have moved forward three times of the array and then back one time.

One more thing you should know that what will happen if we use next() function beyond the last item or prev() function before the first?..like as:

  1. prev($Capitals);
  2. $current_index = key($Capitals);
  3. $current_item = Current($Capitals);
  4. echo ($current_index);
  5. echo ($current_item );

output will be nothing at all, this will not give any error(Thanks php) like some other languages.


Viewing all articles
Browse latest Browse all 5

Trending Articles