+

PHP Print the last value of an array without affecting the pointer

Examples:
Input: $arr = array (`c1` = >` Red`, `c2` = ​​>` Green`, `c3` = >` Blue`, ` c4` = > `Black`) Output: Black Input: $arr = array (` p1` = > `New York`,` p2` = > `Germany`,` p3` = > `England`, `p4` = >` France`) Output: France
The above problem can be easily solved with PHP. The idea is to create a copy of the original array and then use the built-in array_pop()function to get the last value of the array. Since we are using array_pop() on the copy array, the original array pointer remains unchanged.Built-in function used :
  • array_pop() : function used to remove or retrieve the last element of the array.
Below is the implementation of the above approach: // Input Array $array = array ( ` c1` = > `Delhi` , ` c2` = > `Kolkata` , `c3` = > `Mumbai` , ` c4` = > `Bangalore` ); // Copied array $copyArray = $array ; // get the last element from the copied array $lastElement = array_pop ( $copyArray ); // display the last element in the array print_r ( $lastElement . "" ); // display the original array print_r ( $array );  
?>
Output:
Bangalore Array ( [c1] = > Delhi [c2] = > Kolkata [c3] = > Mumbai [c4] = > Bangalore)
Get Solution for free from DataCamp guru