Check array key and replace if exist Php

Solution:

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
)
*/

Answer

Solution:

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
        )

)

Source