note 79449 deleted from ref.array by felipe
| From: | felipe@php.net | Date: | Sun, 30 Dec 2007 19:31:17 +0000 |
| Subject: | note 79449 deleted from ref.array by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-134536@lists.php.net to get a copy of this message | ||
Note Submitter: ashwin dot date at tekdi dot net
----
This function will multiply all elements in an array with a number or float you specify. You can
also multiply elements in an array with corresponding elements in another array. I have used the
index checker script by Nicolai Bloch.
<?php
//Check for numeric array
function isNumeric($ar) {
$keys = array_keys($ar);
natsort($keys); //String keys will be last
return is_int(array_pop($keys));
}
//Check for associative array
function isAssoc($ar) {
$keys = array_keys($ar);
natsort($keys); //Numeric keys will be first
return is_string(array_shift($keys));
}
// Multiply elements of $array
// @arg $array is the array to perform multiplication on
// @arg $input - If it is a number, all elements from $array are multipled by $input
// If $input is an array, elements in $array are multiplied by corresponding elements $input
//
function array_multiplier($array, $input, $maintain_index = true) {
if (is_array($input)) {
$array_values = array_values($array);
$array_keys = array_keys($array);
$input_values = array_values($input);
if (count($array_values) == count($input_values)) {
for ($i=0;$i<=(count($array_values));$i++) {
if (isAssoc($array) && $maintain_index) {
$return->$array_keys[$i] = $array_values[$i] * $input_values[$i];
} else {
$return[$array_keys[$i]] = $array_values[$i] * $input_values[$i];
}
}
} else {
$return = 'Both arrays need to be of same size';
}
} elseif (is_float($input) || is_int($input)) {
foreach ($array as $k=>$v) {
$return->$k = $v * $input;
}
} else {
$return = 'Multiplier not defined';
}
return $return;
}
?>