0

How to save specific items from array using array keys.

INPUT:

$arr = [
    0 => 'item0',
    2 => 'item2',
    4 => 'item4',
    43 => 'item43'
];

Now I only want to save keys 2 and 43.

Expected Output:

$arr = [
   2 => 'item2',
   43 => 'item43'
];

Current Code:

foreach ($arr as $key => $value) {
   if(!($key == 2 || $key == 43)) {
       unset($arr[$key]);
   }
}

It works for now, but what if i have more array keys to save.

1

3 Answers 3

2

You can try this one. Here we are using array_intersect_key and array_flip

array_intersect_key Computes the intersection of arrays using keys.

array_flip will flip array over keys and values.

Try this code snippet here

<?php
ini_set('display_errors', 1);

$arr = [
    0 => 'item0',
    2 => 'item2',
    4 => 'item4',
    43 => 'item43'
];

$keys= [
    2,
    43
];
$result=array_intersect_key($arr, array_flip($keys));
print_r($result);

Solution for current code try here.

You should use != and with && instead of ||

foreach ($arr as $key => $value) 
{
   if($key != 2 && $key != 43) 
   {
       unset($arr[$key]);
   }
}
print_r($arr);
Sign up to request clarification or add additional context in comments.

2 Comments

This is what i am looking for. Thanks
@just_a_simple_guy Glad to help you friend... :)
1

try this code

        <?PHP
    $mykeys=array(2,5,9,7,3,4);

    foreach ($arr as $key => $value) {
       if(!(in_array($key,$mykeys) {
           unset($arr[$key]);
       }
    }?>

Comments

1

you can put the keys you want to keep in an array then iterate over it like this:

$keys = array(); // put the keys here
foreach ( $arr as $key => $value) {
  $found = 0;
  foreach($keys as $filterKey) {
    if ($key == $filterKey) {
      $found = 1;
      break;
    }
    $found = 0;
  }
  if ($found == 0) {
    unset($arr[$key]);
  }
}

Comments

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.