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.

4
  • Try to be more specific on your question, how many options? always 4? unlimited? what did you try? Also please tag PHP so it will be visible on relevant category. Commented Nov 28, 2016 at 6:03
  • Sorry @phobia82 one minute I update. Commented Nov 28, 2016 at 6:04
  • paste your expected output + what have you tried to accomplish it? Commented Nov 28, 2016 at 6:11
  • foreach($array as $key => $value) {, use $key and start with that Commented Nov 28, 2016 at 6:16

2 Answers 2

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>';
Sign up to request clarification or add additional context in comments.

1 Comment

Welcome @Ramkishan! :)
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";
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.