Home > Net >  How do I add a foreach inside another foreach in this context?
How do I add a foreach inside another foreach in this context?

Time:02-28

When a user registers on my platform, there's some code that removes invisible characters.

I wanted to go further and add ucwords into it. However, I need to have some exceptions, as some words in Portuguese names aren't supposed to be capitalized.

The code has one if statement and an else one. I don't know how to change the else statement to correspond to the same thing as my if statement, because it's already a foreach loop.

    $exceptions = array('DAS' => 'das', 'DA' => 'da', 'DE' => 'de', 'DOS' => 'dos', 'DO' => 'do');

    if ( !\is_array( $return ) )
    {
        $return = preg_replace( '/\p{C} /u', '', $return );
        $return = ucwords( $return );
        foreach ( $exceptions as $exception => $fix )
        {
            $return = str_replace( $exception, $fix, $return );
        }
    }
    else
    {
        foreach( $return as $k => $v )
        {
            $return[ $k ] = preg_replace( '/\p{C} /u', '', $v );
            $return[ $k ] = ucwords( $v );
            //What do I add below? How do I type another foreach instead this one?
        }
    }

EDIT:

Would this make sense? If so, why?

    else
    {
        foreach( $return as $k => $v )
        {
            $return[ $k ] = preg_replace( '/\p{C} /u', '', $v );
            $return[ $k ] = ucwords( $v );
            //Does this make sense?
            foreach ( $exceptions as $k => $v )
            {
                $return = str_replace( $k, $v, $return );
            }
        }
        }

CodePudding user response:

The code between array and non-array are the same, so you can write a single foreach

$return = (array)$return;
foreach ($return as $k => $v) {
    $return[ $k ] = preg_replace( '/\p{C} /u', '', $v );
    $return[ $k ] = ucwords( $v );
    foreach ( $exceptions as $exception => $fix ) {
            $return[$k] = str_replace( $exception, $fix, $return[$k] );
    }
}

Alternatively, this is what you'd use a function for

function fix_things($s) {
    $exceptions = array('DAS' => 'das', 'DA' => 'da', 'DE' => 'de', 'DOS' => 'dos', 'DO' => 'do');

    $s = preg_replace( '/\p{C} /u', '', $s );
    $s = ucwords( $s );
    foreach ( $exceptions as $exception => $fix )
        {
            $s = str_replace( $exception, $fix, $s );
        }
    return $s;
}

Then call that function from your main code

if (!\is_array($return)) {
    $return = fix_things($return);
else {
    foreach ($return as $k => $v) {
        $return[$k] = fix_things($v);
    }
}
  •  Tags:  
  • php
  • Related