php - get items from array which index starting with given prefix with array_intersect_key function

php
voted: 0
vote
array php

php - get items from array which index starting with given prefix with array_intersect_key function

<?php

$fruitsAndTools = array(
	'fruit_1' => 'apple',
	'fruit_2' => 'cherry',
	'tool_1' => 'hammer',
	'fruit_3' => 'pineapple'
	);
	
	//get only items with index starting with 'fruit_'
	
	$fruits = array_intersect_key($fruitsAndTools, array_flip(preg_grep('/^fruit_/', array_keys($fruitsAndTools))));
	
	print_r($fruits);
	
        //result
       // Array
       //        (
       //            [fruit_1] => apple
       //             [fruit_2] => cherry
       //            [fruit_3] => pineapple
       //         )

?>
working url: not entered
version: not entered
Leave a Comment:
Characters left:
No comments yet.