OPOPO
OPOPO

Reputation: 503

PHP - Move items from array to array with key LIKE

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
);

Upvotes: 0

Views: 106

Answers (4)

Nik Drosakis
Nik Drosakis

Reputation: 2348

foreach (array_keys($array1) as $key) {
    if (!preg_match('/^key\d+/', $key)) {
        unset($array1[$key]);
    }
}
print_r ($array1);   

Upvotes: 1

Jon
Jon

Reputation: 4736

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
)

Have fun!

Upvotes: 2

$array2 = array();
   foreach($array1 as $key => $val) {
     if(strpos($key,'key')!==false){
        $array2[$key] = $val; //Copy all the values that have key-name like 'key'.
        unset($array1[$key]); //Removes the copied key and value.
     }
   }

Upvotes: 3

elclanrs
elclanrs

Reputation: 94101

$result = array();
foreach ($array as $key => $value) {
  if (strpos($key, 'key') !== false) {
    $result[$key] = $value;
  }
}

Upvotes: 2

Related Questions