PHP Get All Array Keys Starting with Certain String Example
Hello,
In this example, you will learn php get all array keys starting with certain string. it's simple example of php array filter only certain keys. we will help you to give example of get all keys value starting with certain string php array. it's simple example of php array array_filter. Let's see bellow example php array get all keys start with certain string.
i will give you two examples here.
let's see one by one.
Example 1:
<?php
$myArray = [
'hd-1' => 'One',
'hd-2' => 'Two',
'3' => 'Three',
'hd-4' => 'Four',
];
$result = [];
$startWith = 'hd';
foreach($myArray as $key => $value){
$exp_key = explode('-', $key);
if($exp_key[0] == $startWith){
$result[] = $value;
}
}
print_r($result);
?>
Output
Array
(
[0] => One
[1] => Two
[2] => Four
)
Example 2:
<?php
$myArray = [
'hd-1' => 'One',
'hd-2' => 'Two',
'3' => 'Three',
'hd-4' => 'Four',
];
$resultArray = array_filter($myArray, function($key) {
return strpos($key, 'hd-') === 0;
}, ARRAY_FILTER_USE_KEY);
print_r($resultArray);
?>
Output
Array
(
[0] => One
[1] => Two
[2] => Four
)
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Convert Array Key to Lowercase in PHP?
- How to Convert Array Values to Lowercase in PHP?
- How to Remove Specific Element by Value from Array in PHP?
- How to Remove undefined Value from Array in JQuery?
- How to Get Maximum Key Value of Array in PHP?
- How to Remove Empty Values from Array in PHP?
- How to Add Prefix in Each Key of PHP Array?
- How to Get Minimum Key Value of Array in PHP?
- How to Remove Null Values from Array in PHP?
- Laravel Order By with Column Value Example