Ramkishan Ramkishan - 9 days ago 5
PHP Question

How to extract specific key string from array in php?

This is my array


Array
(
[question_set] => Computer Basics
[question] => Who are You ?
[options_1] => RK
[options_2] => KAMAL
[options_3] => DPK
[options_4] => NARENDRA
[marks] => 5
[negative_marks] => 1
[type] => 1
)


options_ are dynamic means it can be 4, 6 or 8.

I want to get value "options" from key of options_1 or so on. How can I do this.

Answer

strpos is way faster than preg_match, for reference: strpos() vs preg_match()

Using foreach and strpos() :

$arr = array(
        "question_set" => "Computer Basics",
        "question" => "Who are You ?",
        "options_1" => "RK",
        "options_2" => "KAMAL",
        "options_3" => "DPK",
        "options_4" => "NARENDRA",
        "marks" => 5,
        "negative_marks" => 1,
        "type" => 1
    );

$newArr = array();
foreach($arr as $key => $value) {
   if(strpos($key, "options") !== false) {
       $newArr[$key] = $value;
   }
}

echo '<pre>';
    var_dump($newArr);
echo '</pre>';