tags:

views:

111

answers:

6

Hello.

I've created this method to change every value in an array. I'm kinda new to PHP, so I think there should be a more efficient way to do this.

Here's my code:

foreach($my_array as $key => $value)
{
     $my_array[$key] = htmlentities($value);
}

Is there a better way to do this?

Thank you in advance.

+3  A: 

When you need to apply a function to the value and reassign it to the value, Galen's answer is a good solution. You could also use array_walk(), although it doesn't read as easily as a nice, simple loop.

When you only need to assign, for example, a primitive value to each element in the array, the following will work.

  • If your keys are numeric, you can use array_fill():

    array_fill(0, sizeof($my_array), "test");
    
  • If you're using an associative array, you can probably use array_fill_keys(), with something like:

    array_fill_keys(array_keys($my_array), "test");
    
Rob Hruska
This answer was written before the edit - the question previously had the loop assigning the value "test" to each array element. It's been updated with an assignment of htmlentities($value), which is more complex than just a simple string assignment.
Rob Hruska
I had the same 'problem' with my answer.
Blair McMillan
+1  A: 

If you mark $value as a reference (&$value) any change you make on $value will effect the corresponding element in $my_array.

foreach($my_array as $key => &$value)
{
   $value = "test";
}

e.g.

$my_array = array(1,2,3,4,5,6);
foreach($my_array as &$value)
{
  $value *= 5;
}
echo join($my_array, ', ');

prints

5, 10, 15, 20, 25, 30

(And there's also array_map() if you want to keep the original array.)

VolkerK
+1  A: 

You could use array_fill, starting at 0 and going to length count($my_array). Not sure if it's better though.

Edit: Rob Hruska's array_fill_keys code is probably better depending on what you define as better (speed, standards, readability etc).

Edit2: Since you've now edited your question, these options are now no longer appropriate as you require the original value to be modified, not changed entirely.

Blair McMillan
+3  A: 

You can reference the array and change it

foreach ($array as &$value) {
    $value = $value * 2;
}
Galen
+1  A: 
foreach($my_array as &$value)
{
    $value = "test";
}
cballou
+5  A: 

You'd probably be better off with array_map

$my_array = array_map( 'htmlentities' , $my_array);
Simon