使用特定键保存项目数组

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.

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

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]);
       }
    }?>

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