1

I have an array of values in PHP looking something like this:

$test = array (  
    array( 'val' => 2, 'color' => 'blue' ),  
    array( 'val' => 5, 'color' => 'green' ),  
);

I want to go through all elements of $test and add 1 to all val indices. Now I realize a foreach loop could work, but I am looking for something a little more efficient. The array will potentially have 10's of thousands of elements and hundreds of sub-elements.

I am wondering if there is some type of way that PHP can go through and modify just that index throughout the entire array, based on the argument that I set.

7
  • 2
    table...columns, so are you working with SQL or PHP arrays here? Commented Mar 14, 2012 at 18:47
  • I am working with PHP as I stated in the question. I am simply calling it a table because it is easier to visualize a table with many columns and you are editing a column throughout all data points. A 2d array is essentially just a simplified table Commented Mar 14, 2012 at 18:51
  • You have not told why foreach isn't efficient. Who says that? Commented Mar 14, 2012 at 18:52
  • 2
    perhaps because it reinvents the wheel. Doing something simple for each collumn of an array can be done with array_walk or array_map. Commented Mar 14, 2012 at 18:55
  • I do not think that foreach would be inefficient speed wise, I should have clarified that I want something cleaner programming wise. I may need to do this many times so it is worth it to me to find out if php already has such functionality before I build my own, no point in reinventing what has already been made Commented Mar 14, 2012 at 18:55

1 Answer 1

1

you can use array_walk and a closure to do it

array_walk($yourArray,function(&$col){$col['val']++});
Sign up to request clarification or add additional context in comments.

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.