PHP Get All Array Keys Starting with Certain String Example

By Hardik Savani May 14, 2024 Category : PHP

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...

Tags :
Shares