Skip to content

Instantly share code, notes, and snippets.

@jarrettbarnett
Last active July 17, 2017 23:50
Show Gist options
  • Save jarrettbarnett/2c07d1aa0bbb6939f99187983d1add5c to your computer and use it in GitHub Desktop.
Save jarrettbarnett/2c07d1aa0bbb6939f99187983d1add5c to your computer and use it in GitHub Desktop.
<?php namespace JB;
/**
* Class NumberHelper Test
* @package JB
* @author Jarrett Barnett <hello@jarrettbarnett.com>
*/
class NumberHelper
{
/**
* Get Sum of Values Squared By Array Key
*
* @param array $data
* @param string $key
* @return bool|number
*/
public function getSumSquaresOfDataForKey($data = array(), $key = '')
{
if (!is_array($data))
{
return false;
}
// array_column requires PHP 5.5+
$squares = $this->getSquareOfValues(array_column($data, $key));
$sums = $this->getSumOfValues($squares);
return $sums;
}
/**
* Get Sum of Values
*
* @param null $input|mixed - returns the sum of an array containing only numbers
* @return bool|number - false on invalid input, sum of values on success
*/
public function getSumOfValues($input = NULL)
{
// check for arrays
if (!is_array($input))
{
// we can only sum numbers/integers
if (!is_numeric($input))
{
return false;
}
// convert value to simple array
$input = [$input];
}
return array_sum($input);
}
/**
* Get Square of Values
*
* @param null $input
* @return array|bool
*/
public function getSquareOfValues($input = NULL)
{
$result = [];
// process input
foreach ($input as $value)
{
// only process numbers
if (!is_numeric($value))
{
continue;
}
$result[] = pow($value, 2);
}
return $result;
}
}
// use our number helper class
$data = array(
array('id' => 5, 'amount' => 10),
array('id' => 6, 'amount' => 12),
array('id' => 7, 'amount' => 4),
array('id' => 8, 'amount' => 'apple'), // ignore this
array('id' => 9) // ignore this
);
$numberHelper = new NumberHelper();
echo $numberHelper->getSumSquaresOfDataForKey($data, 'amount');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment