Tutorialspoint.dev

PHP | Program to move (key,value) pair upwards or downwards


Given an array with key, value pair, we need to move specific value upwards or downwards using the key.

Examples:

Input : $continents = array(
                      'First' => 'Asia',
                      'Second' => 'Europe',
                      'Third' => 'North America',
                      'Fourth' => 'South America',
                            );
        move_to_up($continents, 'Third');
Output : Array
(
    [Third] => North America
    [First] => Asia
    [Second] => Europe
    [Fourth] => South America
)

Input :$continents = array(
                      'First' => 'Asia',
                      'Second' => 'Europe',
                      'Third' => 'North America',
                      'Fourth' => 'South America',
                            );
       move_to_bottom($continents, 'Second');
Output : Array
(
    [First] => Asia
    [Third] => North America
    [Fourth] => South America
    [Second] => Europe
)

The above problem can be solved using the PHP function described below :
unset() : The function destroys the specified variable.

Approach : We prepare a temporary array with specified key (value to be moved up or at the bottom), then we unset the key finally we append depending upon the purpose of whether of moving the value up or at bottom.

Below is the implementation of approach
Code 1 : Moving the key, value at the top



<?php
         
        $continents = array(
                      'First' => 'Asia',
                      'Second' => 'Europe',
                      'Third' => 'North America',
                      'Fourth' => 'South America',
                            );
         
        move_to_up($continents, 'Third');
        print_r ($continents);
  
function move_to_up(&$continents, $string)
       {
           $var = array($string => $continents[$string]);
           unset($continents[$string]);
           $continents = $var + $continents;
       }
?>

Output:

Array
(
    [Third] => North America
    [First] => Asia
    [Second] => Europe
    [Fourth] => South America
)

Code 2 : Moving the key, value at the bottom

<?php
         
        $continents = array(
                      'First' => 'Asia',
                      'Second' => 'Europe',
                      'Third' => 'North America',
                      'Fourth' => 'South America',
                            );
       move_to_bottom($continents, 'Second');
       print_r ($continents);
  
 function move_to_bottom(&$continents, $string)
       {
           $var = array($string => $continents[$string]);
           unset($continents[$string]);
           $continents = $continents + $var;
       }
         
?>

Output:

Array
(
    [First] => Asia
    [Third] => North America
    [Fourth] => South America
    [Second] => Europe
)


This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter