ʞɹᴉʞ ǝʌɐp
ʞɹᴉʞ ǝʌɐp

Reputation: 5650

How to multiply all array element at once without iteration in php?

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 might affect the performance ...

Deepak

Upvotes: 0

Views: 2547

Answers (5)

Behnam Bakhshi
Behnam Bakhshi

Reputation: 273

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

Upvotes: 0

Gordon
Gordon

Reputation: 317119

"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

This would still leave you iterating, but for large datasets, those datastructures can make a difference in both execution speed and memory consumption.

Upvotes: 1

Your Common Sense
Your Common Sense

Reputation: 157877

Well because of bunch of deleted answers, which were right ones.

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

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

  3. If you came to that point anyway, the fastest way is a matter of test. it seems aaray_map is worst one.

Upvotes: 0

alex
alex

Reputation: 490403

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

Upvotes: 0

Luke Stevenson
Luke Stevenson

Reputation: 10341

function multiplyElements( $inElem ){
  return $inElem * n; // Where "n" is the number to multiply all elements by
}

$yourArray = array_map( 'multiplyElements' , $yourArray );

Upvotes: 1

Related Questions