Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace underscore with space and upper case first character in array

Tags:

arrays

php

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?

like image 202
Sadikhasan Avatar asked Apr 02 '15 05:04

Sadikhasan


1 Answers

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)
like image 124
agamagarwal Avatar answered Oct 15 '22 19:10

agamagarwal