Search code examples
phparraysstring

Pass comma separated key string and get value of array according to key in PHP


I am trying to get value from array and pass only comma separated key string and get same output without. Is it possible without using foreach statement. Please suggest me.

<?php
$str = "1,2,3";
$array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");

$keyarray = explode(",",$str);
$valArr = array();
foreach($keyarray as $key){
   $valArr[] = $array[$key];
}
echo $valStr = implode(",", $valArr);    
?>    

Output : apple,banana,orange


Solution

  • Use array_intersect_key

    $str = "1,2,3";
    $array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");
    
    $keyarray = explode(",",$str);
    echo implode(",", array_intersect_key($array, array_flip($keyarray)));
    

    https://3v4l.org/gmcON


    One liner:

    echo implode(",", array_intersect_key($array, array_flip(explode(",",$str))));
    

    A mess to read but a comment above can explain what it does.
    It means you don't need the $keyarray