0

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
);
6
  • @YogeshSuthar That's cheating! Commented Apr 6, 2013 at 6:40
  • Write a foreach loop that checks the key and decides whether to copy the key and value to the result. What's the problem? Commented Apr 6, 2013 at 6:41
  • 1
    @YogeshSuthar haha! Nice avoidance of the filter +1 Commented Apr 6, 2013 at 6:41
  • @Barmar What cheating? Can you explain? I am not getting. Commented Apr 6, 2013 at 6:41
  • @YogeshSuthar You misspelled "have" to get around SO's block on comments that just say "What have you tried?" Commented Apr 6, 2013 at 6:42

4 Answers 4

3
$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.
     }
   }
2

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!

2
$result = array();
foreach ($array as $key => $value) {
  if (strpos($key, 'key') !== false) {
    $result[$key] = $value;
  }
}
1
foreach (array_keys($array1) as $key) {
    if (!preg_match('/^key\d+/', $key)) {
        unset($array1[$key]);
    }
}
print_r ($array1);   
1
  • 1
    It doesn't create the second array and using an intensive and unnecessary preg_match to assert the beginning position - when it was asked for like not "starts with" ^^ Instead of preg_match could use substr($key,0,3) == 'key' (also was never specified to have digits following =] ) Commented Apr 6, 2013 at 7:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.