PHP Array Exercises : Get the last value of an array without affecting the pointer
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:
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics