note 79449 deleted from ref.array by felipe

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
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;
	
	}

?>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.