Thursday, 30 August 2018

PHP - Moves the array elements to the array with the key

Lets say we have array:

$array1 = array (
    'key1' => 1,
    'non1' => 1,
    'key2' => 1,
    'non2' => 1,
    'non3' => 1,
    'non4' => 1,
    'key3' => 1,
    'key4' => 1
);

How to move all the keys that have key name LIKE "key" and move them to another array.
$array2 = movekey('key',$array1);

Would give:
array1 = array (
    'non1' => 1,
    'non2' => 1,
    'non3' => 1,
    'non4' => 1

);

array2 = array (
    'key1' => 1,
    'key2' => 1,
    'key3' => 1,
    'key4' => 1
);


Just because it seemed fun, put it in function form per OP's original wish:
function moveKey($cmp, Array & $ar)
{
    $y = array();
    foreach($ar as $key => $value) {
        if(strpos($key, $cmp) !== false) {
            $y[$key] = $value;
            unset($ar[$key]);
        }
    }
    return $y;
}

and then to test the function:
$array1 = array (
    'key1' => 1,
    'non1' => 1,
    'key2' => 1,
    'non2' => 1,
    'non3' => 1,
    'non4' => 1,
    'key3' => 1,
    'key4' => 1
);

$a2 = moveKey('key', $array1);
echo "<pre>". print_r($array1, true) ."\n". print_r($a2, true) ."</pre>";

And it outputs:
Array
(
    [non1] => 1
    [non2] => 1
    [non3] => 1
    [non4] => 1
)

Array
(
    [key1] => 1
    [key2] => 1
    [key3] => 1
    [key4] => 1
)

0 comments:

Post a Comment