w3resource

PHP Array Exercises : Get the last value of an array without affecting the pointer

PHP Array: Exercise-50 with Solution

Write a PHP script to get the last value of an array without affecting the pointer.

Sample Solution:

PHP Code:

<?php
// Original associative array
$colors = array('c1' => 'Red',  'c2' => 'Green',  'c3' => 'White',  'c4' => 'Black');
// Move the internal pointer to the next element and return its value
echo next($colors) . "\n";
// Use array_flip to swap keys and values, then array_keys to get the keys
$keys = array_keys(array_flip($colors));
// Use array_pop to get the last element
$last = array_pop($keys);
echo $last . "\n";
// Move the internal pointer to the first element and return its value
echo current($colors) . "\n";
  
?>

Output:

Green                                                       
Black                                                       
Green

Flowchart:

Flowchart: PHP - Get the last value of an array without affecting the pointer

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP script to get an array containing all the entries of an array which have the keys that are present in another array.
Next: Write a PHP program to filter out some array elements with certain key-names.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/php-array-exercise-50.php