Sadikhasan
Sadikhasan

Reputation: 18600

Replace underscore with space and upper case first character in array

I have the following array.

$state = array("gujarat","andhra_pradesh","madhya_pradesh","uttar_pradesh");

Expected Output

$state = array("Gujarat","Andhra Pradesh","Madhya Pradesh","Uttar Pradesh");

I want to convert array values with each first character of a word with UpperCase and replace _ with space. So I do it using this loop and it working as expected.

foreach($states as &$state)
 {
    $state = str_replace("_"," ",$state);
    $state = ucwords($state);
 }

But my question is: is there any PHP function to convert the whole array as per my requirement?

Upvotes: 20

Views: 34608

Answers (4)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

Need to use array_map function like as

$state = array("gujarat","andhra_pradesh","madhya_pradesh","uttar_pradesh");
$state = array_map(upper, $state);
function upper($state){
    return str_replace('_', ' ', ucwords($state));
}
print_r($state);// output Array ( [0] => Gujarat [1] => Andhra pradesh [2] => Madhya pradesh [3] => Uttar pradesh )

Upvotes: 4

PravinS
PravinS

Reputation: 2584

Use array_map() function

<?php
    function fun($s)
    {
        $val = str_replace("_"," ",$s);
        return ucwords($val);
    }
    $state = array("gujarat","andhra_pradesh","madhya_pradesh","uttar_pradesh");
    $result = array_map('fun',$state);
    print_r($result);
?>

Upvotes: 1

agamagarwal
agamagarwal

Reputation: 988

You can use the array_map function.

function modify($str) {
    return ucwords(str_replace("_", " ", $str));
}

Then in just use the above function as follows:

$states=array_map("modify", $old_states)

Upvotes: 42

phpPhil
phpPhil

Reputation: 926

PHP's array_map can apply a callback method to each element of an array:

$state = array_map('makePretty', $state);

function makePretty($value) 
{
    $value= str_replace("_"," ",$value);
    return ucwords($value);
}

Upvotes: 2

Related Questions