Saturday, February 7, 2026
HomeLanguagesPHP | Print the last value of an array without affecting the...

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

We are given an array with key-value pair, and we need to find the last value of array without affecting the array 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 using PHP. The idea is to create a copy of the original array and then use the array_pop() inbuilt function, to get the last value of the array. As we are using the array_pop() function on the copy array, so the pointer of the original array remains unchanged.

Built-in function used:

  • array_pop(): The function is used to delete or pop the last element of an array.

Below is the implementation of the above approach:




<?php
      
    // Input Array
    $array = array('c1' => 'Delhi', 'c2' => 'Kolkata', 
                    'c3' => 'Mumbai', 'c4' => 'Bangalore');
          
    // Copied Array
    $copyArray = $array;
      
    // getting last element from Copied array    
    $lastElement = array_pop($copyArray);
          
    // displaying the last element of the array 
    print_r($lastElement."\n");
          
    // displaying the original array
    print_r($array);
          
?>    


Output:

Bangalore
Array
(
    [c1] => Delhi
    [c2] => Kolkata
    [c3] => Mumbai
    [c4] => Bangalore
)
RELATED ARTICLES

Most Popular

Dominic
32491 POSTS0 COMMENTS
Milvus
126 POSTS0 COMMENTS
Nango Kala
6863 POSTS0 COMMENTS
Nicole Veronica
11987 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12076 POSTS0 COMMENTS
Shaida Kate Naidoo
6996 POSTS0 COMMENTS
Ted Musemwa
7238 POSTS0 COMMENTS
Thapelo Manthata
6947 POSTS0 COMMENTS
Umr Jansen
6933 POSTS0 COMMENTS