Replace underscore with space and upper case of first character in array

I have the following array.

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

Expected Result

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

I want to convert array values ​​with every first character of a word using UpperCase and replace _ with space . So I do this using this loop, and it works 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 entire array according to my requirement?

+7
arrays php
source share
4 answers

You can use the array_map function.

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

Then just use the above function as follows:

 $states=array_map("modify", $old_states) 
+17
source share

You must use the array_map function 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 ) 
+4
source share

PHP array_map can apply a callback method to each element of the array:

 $state = array_map('makePretty', $state); function makePretty($value) { $value= str_replace("_"," ",$value); return ucwords($value); } 
+1
source share

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); ?> 
+1
source share

All Articles