Forum Moderators: coopster
// THE FUNCTION ITSELF
// *******************
function mod_array ($var) {
echo "<br>".$var[0]."<br>";
// ADD "CHOCO" IF CAKE
if ($var[0]=="cake") {$var[]="choco";}
return $var;}// ARRAY
// *****
$text_array=array("cake", "sweet");
$nb=count($text_array);// LOOP & FUNCTION CALL
// ********************
for($i=0; $i<$nb; $i++){
// MAKE A NEW ARRAY FOR EACH ELEMENT OF THE ARRAY
$new_array=array($text_array[$i]);// PRINT NEW ARRAY AFTER THE FUNCTION IS CALL
// THIS METHOD DOESN'T WORK
mod_array ($new_array); print_r ($new_array);// THIS METHOD WORKS
// print_r (mod_array($new_array));
}
Any idea why?
Any help would really appreciated.
Thank you
1. What you expected to happen
2. What actually happened
From what you've provided, here's my stab in the dark.
mod_array ($new_array); will not alter the contents of $new_array. mod_array only returns a new array, it doesn't modify the variable you pass to it. So, you need to say
$new_array = mod_array($new_array); If you want to make your mod_array function modify the variable that you pass to it (like the built in array sort functions), you must pass the value by reference. You can do that by using the & symbol in your function declaration.
function mod_array (& $var) {...} This can often have unintended consequences, and I wouldn't use it until you understand how PHP works a little better.
I am sure it is a simple one!
Change:
function mod_array ($var) {
echo "<br>".$var[0]."<br>";
// ADD "CHOCO" IF CAKE
if ($var[0]=="cake") {
$var[]="choco";
}
return $var;
}
To:
function mod_array (&$var) {
echo "<br>".$var[0]."<br>";
// ADD "CHOCO" IF CAKE
if ($var[0]=="cake") {
$var[]="choco";
}
}
Or leave the function and change:
mod_array ($new_array);
To:
$new_array = mod_array ($new_array);
Hopefully this saves you three more hours. Enjoy!
As I suppose this is the corrected version: (function is correct)
<?php
...
$text_array=array("cake", "sweet");
$nb=count($text_array);// LOOP & FUNCTION CALL
// ********************
for($i=0; $i<$nb; $i++){
// MAKE A NEW ARRAY FOR EACH ELEMENT OF THE ARRAY
$new_array[]] = mod_array(array($text_array[$i]));//don't rewrite the new_array and mod_array needs argument that is single array, not double.
}
// PRINT NEW ARRAY AFTER THE FUNCTION IS CALL
print_r ($new_array);
?>