PHP Get All Array Keys Starting with Certain String Example

By Hardik Savani | January 25, 2021 | 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 : Array PHP


Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. 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, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.

We are Recommending you: