php - Foreach loops and references

100

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

224

Answer

Solution:

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.

People are also looking for solutions to the problem: php - Variable not being passed to second select dropdown

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.