2

I have a very little piece of code for testing an array_walk test.

I thought that I could do the same with foreach but then when I pass the value it doesn't get modified:

<?php
$frutas = [ "d" => "limón", "a" => "naranja", "b" => "banana", "c" => "manzana" ];

function test_alter(&$elemento)
{
  $elemento = "prefijo: $elemento";
  echo "$elemento <br>";
}

foreach($frutas as $clave => $valor) {
  test_alter($valor, $clave);
}
print_r( $frutas ); 
?>

Which outputs:

prefijo: limón
prefijo: naranja
prefijo: banana
prefijo: manzana
Array ( [d] => limón [a] => naranja [b] => banana [c] => manzana ) 

Obviously not modifying array value although its passed by reference.

1 Answer 1

5

You are passing $valor to the function ... foreach values are not 'referenced' values, so you are altering a temporary value, not the actual array value ...

try this in your foreach loop:

test_alter($frutas[$clave]);

or, you could:

foreach($frutas as $clave => &$valor){
    test_alter($valor, $clave);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, both worked but I noticed in the second example that its not necessary to pass $clave to test_alter isnt it? (I deleted it and got the same result).
I was just using the code you had ... you are passing $clave in your original example ... I agree that it is not necessary, as your test_alter function does not accept a second parameter
Oh, was my mistake (I was editing it and trying different things). Thanks a lot for your time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.