20

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?

3
  • 1
    create a string replacement function, the array_map it is another way. you said its working fine, why the change? Commented Apr 2, 2015 at 5:47
  • @Ghost It working find with foreach loop but I want short code to implement it Commented Apr 2, 2015 at 6:04
  • oh okay, sure, those answers below should suffice Commented Apr 2, 2015 at 6:04

4 Answers 4

42

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Fulfilled my purpose. But any idea how to use it in the controller in Codeigniter OOPS ? $this->functionname() ?
4

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 )

3 Comments

Your code also short and sweet but you are late. Thanks
Its ok you like it thats enough.. Happy Coding
This code has syntax typos.
2

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);
}

Comments

1

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);
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.