0

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.

Ramkishan Suthar
  • 403
  • 1
  • 7
  • 26

2 Answers2

2

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>';
Community
  • 1
  • 1
L. Herrera
  • 490
  • 4
  • 13
0
<?php

$array = array("options_1"   => "RK",  
               "options_213" => "21313",
               "options_4"   => "NARENDRA",
               "foo"         => "bar", 5 , 5 => 89009,
              );

$pattern = "/\boptions/";

foreach($array as $key => $value) {
    if (preg_match($pattern,$key)){
        echo $key."\t=>\t".$value."\n";
    }
}
solarhell
  • 172
  • 8