How to treat each value of an array without knowing the index name?

Asked

Viewed 137 times

1

Here’s the thing, I’m creating a function that takes an array and turns the writing into uppercase, the code is the following:

function uppercase($post_array) //ok
{
    $post_array['clienteNomeCompleto'] = mb_strtoupper($post_array['clienteNomeCompleto']);

    return $post_array;
}

Well there is the problem, in this example, I know that the value is in the clienteNomeCompleto field, but the other fields I do not know the name, because the same function will receive data from 3 different lists, one from customers, another from suppliers, and another from employees, each with specific fields, so I wanted to know, how do I do this without having to specify the field name? I tried so:

function uppercase($post_array)
{
    $post_array = mb_strtoupper($post_array);
    return $post_array;
}

And so:

function uppercase($post_array) //ok
{
    $count = count($post_array)
   for( $i=0; i<=$count; $i++){
   mb_strtoupper($post_array[$i]);
   }
    return $post_array;
}

Even with a foreach I tried:

    function uppercase($post_array) //ok
{
    foreach ($post_array as $value){
    $value = mb_strtoupper($value);
    }
    return $value;
}

Can someone shed some light on what I’m doing wrong? And if it’s no bother, how do I do the same function, only to remove the characters ,.;:/? | -_()[]{} also.

1 answer

2


Simple, use array_map. It maps every item of array applying the desired function:

$post_array = array_map('mb_strtoupper', $dados);

The way you tried to foreach would have worked if you had used reference in value.

function array_to_upper_case(array $post_array) {

    foreach ($post_array as &$value) {
        $value = mb_strtoupper($value);
    }

    return $post_array;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.