Buttle Butkus
Buttle Butkus

Reputation: 9456

How to write recursive ucwords method

I need all words to be in proper case, with first letters capitalized and others lower case.

I tried:

array_walk_recursive($my_array,'ucwords');

But I guess the function needs to be user-defined.

So I wrote:

function ucrecursive($value,$key) {
    return ucwords($value);
}

array_walk_recursive(&$my_array,'ucrecursive');

Still doesn't work. Any ideas?

EDIT: sample data:

Array
(
    [0] => Array
        (
            [count] => 768
            [value] => SATIN NICKEL
        )

    [1] => Array
        (
            [count] => 525
            [value] => POLISHED CHROME
        )

    [2] => Array
        (
            [count] => 180
            [value] => AGED BRONZE
        )

etc...

Upvotes: 4

Views: 251

Answers (4)

M.abdelrhman
M.abdelrhman

Reputation: 1088

If anyone wants to build it with recursive without any build-in functions

function capitalizeWords ($array) {
 if (count($array) === 1) {
     return [ucwords($array[0])];
 }
 $res = capitalizeWords(array_slice($array,0,-1));
 array_push($res,ucwords(array_slice($array,count($array)-1)[0]));
 return $res;

}

capitalizeWords(['php','javascript','golang']);`

Upvotes: 0

Matoeil
Matoeil

Reputation: 7289

that would be :

array_walk_recursive($my_array,function(&$value) {
    $value = ucwords(strtolower($value));
});

Upvotes: 1

Krycke
Krycke

Reputation: 3176

Should be pretty easy to build it yourself:

function ucWordsRecursive( array &$array ) {
    foreach( $array as &$value ) {
        if( is_array( $value ) ) {
             ucWordsRecursive( $value );
        }
        else if( is_string( $value ) ){
            $value = ucwords( strtolower( $value ) );
        }
    }
}

Upvotes: 2

Madara's Ghost
Madara's Ghost

Reputation: 174937

array_walk_recursive($my_array,function(&$value) {
    $value = ucwords($value);
});

Try this

Upvotes: 3

Related Questions