How to Move From One Array To Another Array In PHP

admin_img Posted By Bajarangi soft , Posted On 16-09-2020

Given an array and migrate 3 elements from that array to another array in PHP

array to another array

1.Create array.

$array1 = array(
    '1' => 'crow',
    '2' => 'peacock',
    '3' => 'sparrow',
    '4' => 'mango',
    '5' => 'banana',
    '6' => 'apple'
);

2.Declare another array to store elements.
$array2 = array();

3.Declare another variable to count the number of iteration .
$number = 0;

4.Create foreach loop for every loop iteration, the value of the current array element is assigned to $val and the array pointer is moved by one, until it reaches the last array element.unset function remove the elements from the
$array1.

 
foreach($array1 as $key => $val){
    if(++$number > 3) break; // we don’t need more than three iterations
    $array2[$key] = $val; // copy the key and value from the first array to the second
    unset($arr1[$key]); // remove the key and value from the first
}

5.Print array elements which moved to another array or you can also use foreach loop .
print_r($array1);
print_r($array2);

6.Complete code for migrating data from an array to another
<!DOCTYPE html>
<html>
<head>
    <title>migrate data from an array to another PHP</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div class="text-center">
        <h1>Migrate data from an array to another PHP</h1>
    </div>
    <br>
    <h2></h2>
    <div class="well">
        <?php
        $array1 = array(
            '1' => 'crow',
            '2' => 'peacock',
            '3' => 'sparrow',
            '4' => 'mango',
            '5' => 'banana',
            '6' => 'apple'
        ); // the first array
        $array2 = array(); // the second array
        $number  = 0; // a variable to count the number of iterations
        foreach($array1 as $key => $val){
            if(++$number > 3) break; // we don’t need more than three iterations
            $array2[$key] = $val; // copy the key and value from the first array to the second
            unset($array1[$key]); // remove the key and value from the first
        }
        echo "<h2>First array</h2>";
        foreach($array1 as  $val){

            echo "<h4>".$val."</h4>";// output the first array
        }
        echo "<br>";
        
        echo "<h2>Second array</h2>";
        foreach($array2 as  $val){

            echo "<h4>".$val."</h4>";// output the second array
        }
        ?>
    </div>
    <br>
</div>
</body>
</html>

Related Post