Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I multiply each item in an array easily with PHP?

Tags:

arrays

php

I have an array called $times. It is a list of small numbers (15,14,11,9,3,2). These will be user submitted and are supposed to be minutes. As PHP time works on seconds, I would like to multiply each element of my array by 60.

I've been playing around with array_walk and array_map but I can't get those working.

like image 526
Sabai Avatar asked Apr 17 '10 21:04

Sabai


People also ask

How do you multiply two values in an array?

C = A . * B multiplies arrays A and B by multiplying corresponding elements. The sizes of A and B must be the same or be compatible. If the sizes of A and B are compatible, then the two arrays implicitly expand to match each other.

How do you multiply numbers in PHP?

The bcmul() function in PHP is an inbuilt function and is used to multiply two arbitrary precision numbers. This function accepts two arbitrary precision numbers as strings and returns the multiplication of the two numbers after scaling the result to a specified precision.


1 Answers

You can use array_map:

array_map() returns an array containing all the elements of arr1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()

Examples with lambda functions for callbacks:

array_map(function($el) { return $el * 60; }, $input);

Same for PHP < 5.3

array_map(create_function('$el', 'return $el * 60;'), $input);

Or with bcmul for callback

array_map('bcmul', $input, array_fill(0, count($input), 60));

But there is nothing wrong with just using foreach for this as well.

like image 53
Gordon Avatar answered Oct 14 '22 18:10

Gordon