I have an array consisting of more than 25k elements. All array values are integer. NOw i want to multiply all elements of this array by some number "n".... how can I do that with out iterating thru each element using a i.e. without using a foreach?
I am looking for this bcoz iterating thru such large array mi开发者_运维技巧ght affect the performance ...
Deepak
function multiplyElements( $inElem ){
  return $inElem * n; // Where "n" is the number to multiply all elements by
}
$yourArray = array_map( 'multiplyElements' , $yourArray );
"might affect the performance" is not a valid reason to optimize. Make sure it does affect performance. If you are sure it negatively affects performance, consider using one of the Spl Data Structures
- http://de.php.net/manual/en/spl.datastructures.php
- http://matthewturland.com/2010/05/20/new-spl-features-in-php-5-3/
This would still leave you iterating, but for large datasets, those datastructures can make a difference in both execution speed and memory consumption.
There is an array_sum(), but not array multiplier function.
You will need to iterate (or use array_map(), which just abstracts the iteration from you).
I would also make sure your number doesn't overflow PHP's max integer size (check PHP_INT_MAX on your platform). You may need to use gcmul().
Well because of bunch of deleted answers, which were right ones.
- You are going to have to iterate over the array somehow. Even using something like array_map() (see other two answers) causes PHP to iterate over the array internally. 
- The best way to optimize 25k iterations is to avoid such large numbers at all. Or at least place it in the background where performance wouldn't be significant. 
- If you came to that point anyway, the fastest way is a matter of test. it seems aaray_map is worst one. 
Use the Nested function like below
function arrayFunc($e){
    if(is_array($e)) return array_map('arrayFunc', $e);
    else return $e; // Set your changes here for example change this line to : else return $e * 1000;
}
$array = arrayFunc($array);
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论