简体   繁体   中英

foreach element of an array, perform a function

sorry for asking so many questions -- I wrote a lot of code today and then started debugging all at once.

I want to run each element of an array through a function, so I chose to do a "foreach" loop. Here is my code:

//Set up mod and polarity associative arrays


$mod_array = array(

"image_mod1" =>     "$page_mod1",
"image_mod2" =>     "$page_mod2",
"image_mod3" =>     "$page_mod3",
"image_mod4" =>     "$page_mod4",
"image_mod5" =>     "$page_mod5",
"image_mod6" =>     "$page_mod6",
"image_mod7" =>     "$page_mod7",
"image_mod8" =>     "$page_mod8"

);

$polarity_array = array(

"image_polarity1" => "$page_polarity1",
"image_polarity2" => "$page_polarity2",
"image_polarity3" => "$page_polarity3",
"image_polarity4" => "$page_polarity4",
"image_polarity5" => "$page_polarity5",
"image_polarity6" => "$page_polarity6",
"image_polarity7" => "$page_polarity7",
"image_polarity8" => "$page_polarity8"

);


foreach($mod_array as $string)
{
    convertImageMod($string);
}

foreach($polarity_array as $string)
{
    convertImagePolarity($string);
}

However, when I echo the string ( echo $page_polarity6; ), the text that echos is as though the function has not been applied.

Here are my function definitions:

function convertImageMod($string)
{
$string = preg_replace('/\s+/', '', $string);
$string = str_replace("'", "", $string);
$stringlength = strlen($string);
$stringlength -= 3;
$string = substr ($string, 0, $stringlength);
$string = strtolower ($string);
$string = "<img src=\"images/items/{$string}.png\">";
return $string;
}

function convertImagePolarity($string)
{
$string = "<img src=\"images/items/{$string}.png\">";
return $string;
}

Am I not doing something here?

Thanks!

The function is probably doing something to the string and returning it (taking a guess. I can't be sure without seeing the function definition). Since you are not doing anything with the return value, you are discarding whatever the function is returning, and thus you ending up with the strings unchanged.

You can either pass the arguments via reference

Or, store the returned result in your array:

foreach ($mod_array as $key=>$val) {
  $mod_array[$key] = convertImageMod($val);
}

Use foreach -loop with reference & to apply results to the array. Example:

foreach($mod_array as &$string){
//                    ^ this
    $string = convertImageMod($string);
//  also, you need to assign return value of a function
//  to the current loop element ($string in this case).
}

Or use array_map() function. Example:

$mod_array = array_map('convertImageMod', $mod_array);

Second option is less efficient and more memory consuming.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM