2

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.

1
  • Are you looking for a more computationally efficient (faster) way, or a more efficient characters of code way (less typing)? I doubt there is one for the former. Commented Dec 9, 2009 at 17:24

6 Answers 6

8

You'd probably be better off with array_map

$my_array = array_map( 'htmlentities' , $my_array);
Sign up to request clarification or add additional context in comments.

Comments

5

You can reference the array and change it

foreach ($array as &$value) {
    $value = $value * 2;
}

Comments

3

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");
    

2 Comments

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.
I had the same 'problem' with my answer.
2

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.)

Comments

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

Comments

1

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.

Comments

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.