Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove array key prefix

Tags:

arrays

php

I have this type of array what contains total income in each month:

Array ( [Total_Income_JAN] => 5000 [Total_Income_FEB] => 8000 [Total_Income_MAR] => 10000 )

How can I remove the prefix part from the array keys so that it becomes:

Array ( [JAN] => 4321 [FEB] => 2364 [MAR] => 2364 ) 
like image 619
user2389411 Avatar asked Dec 15 '22 10:12

user2389411


1 Answers

Try this:

<?php

$list  = Array("Total_Income_JAN" => 5000, "Total_Income_FEB" => 8000 , "Total_Income_MAR" => 10000);

function removePrefix(array $input) {

    $return = array();
    foreach ($input as $key => $value) {
        if (strpos($key, 'Total_Income_') === 0)
            $key = substr($key, 13);

        if (is_array($value))
            $value = removePrefix($value); 

        $return[$key] = $value;
    }
    return $return;
}

$list = removePrefix($list);
print_r($list);

?>

Try Demo>>

like image 164
Vijaya Pandey Avatar answered Jan 05 '23 14:01

Vijaya Pandey