Ronald De Ruiter
Ronald De Ruiter

Reputation: 319

Foreach loops and references

In the following loop:

foreach( $email_field_arrays as $key => $array_of_emails ) {
    if( ! empty( $array_of_emails ) ){
        foreach( $array_of_emails as $i => $email ) {
            $sanitized_email = sanitize_email( trim( $email ) );
            $email_field_arrays[$key][$i] = $sanitized_email;
        }
    }
}

How could i use the '&$...' reference operator so that i would not have to include this line:

$email_field_arrays[$key][$i] = $sanitized_email;

to update the values in the array?

I have searched the internet on how references work but I can't seem to understand them, not in the context of loops or function arguments.

I realize this question is not expressly WordPress related but I believe i am likely to be the only one who has been taking the 'long route' to achieve the sanitation of data in arrays and their code could be improved also.

Many thanks

Upvotes: 0

Views: 49

Answers (1)

moonwave99
moonwave99

Reputation: 22817

You want to hear about the reference operator [&]:

foreach( $email_field_arrays as $key => &$array_of_emails ) {
    if( ! empty( $array_of_emails ) ){
        foreach( $array_of_emails as $i => &$email ) {
            $email = sanitize_email( trim( $email ) );
        }
    }
}

Generally speaking:

foreach($array as $key => &$value){

  $value = someFunction();

}

Now each $value of $array will be updated in place.

Upvotes: 2

Related Questions