planet x planet x - 7 months ago 18
PHP Question

ucwords value in an array

In my $_POST, I am wondering how can I apply ucwords on the value "english" and "math" inside the array.

Array
(
[name1] => Array
(
[0] => english
[1] => 2
)

[name2] => Array
(
[0] => math
[1] => 1
)

[submit] => Add to List
)


I am still confused in manipulating an array, so I tried this, but no luck.

foreach($_POST as $key => $value)
{
if(is_array($value))
{
foreach($value as $key2 => $value2)
{
$value2 = ucwords($value2);
}
}
}

Answer

By changing those values (as with any other variable). As it's an array, this is fundamentally like this (for "english" in your example):

$_POST['name1'][0] = ucwords($_POST['name1'][0]);

You are using a foreach loop to iterate over each of those values, that's basically like the following (again simplified) example (which does not work in your case, just to make this more visible):

$value2 = $_POST['name1'][0];
$value2 = ucwords($value2);

As this example shows, you're changing the value of $value2 but not the according entry in $_POST. You can use a reference or aliasing in PHP to achieve this:

$value2 = &$_POST['name1'][0];
$value2 = ucwords($value2);

This will change $_POST['name1'][0] as well, because it has been aliased Docs as $value2 and now is a reference to it.

foreachDocs does support references as well:

foreach($_POST['name1'] as &$value2)
{
    $value2 = ucwords($value2);
}
unset($value2); # remove the alias for safety reasons.

See the & sign inside the foreach header in front of $value2. This makes $value2 an alias to each array entry while iterating over the array.

As you are iterating over two arrays inside each other, you need to apply this twice, here is the full example:

foreach ($_POST as $key => &$value)
{
    if (is_array($value))
    {
        foreach ($value as $key2 => &$value2)
        {
            $value2 = ucwords($value2);
        }
        unset($value2); # remove alias for safety reasons.
    }
}
unset($value); # remove alias for safety reasons.

Naturally it's possible to prevent aliasing here and access those values directly by using the keys:

foreach ($_POST as $keyOuter => $valueOuter)
{
    if (is_array($valueOuter))
    {
        foreach ($valueOuter as $keyInner => $valueInner)
        {
            $_POST[$keyOuter][$keyInner] = ucwords($valueInner);
        }
    }
}

Which is probably better readable and easier to understand how it works because it does not uses any aliasing/references.