1

I have following array ($result)

Array
(
    [check_1] => Array
        (
            [0] => male
            [1] => female
        )

    [email] => abc@xyz.com
)

I just want to check

  1. Whether array key contain word "check"(id will dynamic, id can be 1 or 2 ...)
  2. If "check" key exist then all values (checkbox) should be like "male,female"
  3. I want to replace "check_1" with "user_1"

I want output like folllowing way

Array
(
    [user_1] => Array
        (
           [0] male,female
        )
  
)

How can i do this ? Thanks in advance

Ritika
  • 11
  • 1

2 Answers2

0

You might have to use loops with functions like str_contains and str_replace and implode for concatenation.

$data = [
            'check_1'=>["male"],
            'email'=>["abc@xyz.com"],
            'check_3'=>["male", "female"],
        ];
$res = [];
foreach ($data as $key => $value) {
    if(strrpos($key, "check")!==false){
        $res[str_replace("check", "user", $key)] = implode(', ', $value);
    }
}
echo "<PRE>";
print_r($res);
/*
Array
(
    [user_1] => male
    [user_3] => male, female
)
*/
XMehdi01
  • 5,538
  • 2
  • 10
  • 34
0

You would use :

foreach($result as $key => $value) {
    if(substr($key,0,6) == 'check_') {
        $id = substr($key, strrpos($key,'_'));
        $result['user' . $id][] = implode(',',$value);
        unset($result[$key]);
    }
}

It will return :

Array
(
    [email] => abc@xyz.com
    [user_1] => Array
        (
            [0] => male,female
        )

)
Thomas
  • 410
  • 9
  • 14