Vijay Kumar Vijay Kumar - 5 months ago 11
PHP Question

How to unset rest of element except then one index in array

Have an array i want to unset rest of element except then one index in array

Array

$array = Array ( "Result" => Array ( "ResponseStatus" => 1, "Hotels" => Array ( Array ( "Rating" => 1, "Description" => "Description1" ), Array ( "Rating" => 2, "Description" => "Description2"), Array ( "Rating" => 4, "Description" => "Description3") ) ) );


Like i want keep only $array['Result']['Hotels'][1] and unset rest of index

Want Output

Array
(
[Result] => Array
(
[ResponseStatus] => 1
[Hotels] => Array
(
[1] => Array
(
[Rating] => 2
[Description] => Description2
)
)
)
)


I have tried this

$arrayKey = 1;
foreach ($array['Result']['Hotels'] as $key => &$value) {
if (!$key == $arrayKey) {
unset($value[$key]);
}
}

Answer

You can use array_intersect_key function creating an array with the desired key (keys). In this case [1=>null];

$array['Result']['Hotels'] = array_intersect_key($array['Result']['Hotels'], [1=>null]);
Comments