calculate the arithmetic elements of php array? - php

this i my array
$arr = array(1,2,3,4,5);
How to get the result that calculate the value of this expression ((((1-2) -3)-4)-5)?

2 times the first entry minus the whole sum - looks pretty quick.
echo (2 * reset($arr)) - array_sum($arr);

Just substract the sum of all elements but the first from the first element:
echo array_shift($arr) - array_sum($arr); # -13
To preserve the array, change the calculation a little:
echo $arr[0]*2 - array_sum($arr); # -13
And we're glad you didn't ask for eval:
echo eval('return '.implode('-', $arr).';'); # -13
However the best suggestion I can give is that you encapsulate the logic into a class and overload the array with it. So that the object than can provide a method for the calculation (Demo):
class Operands extends ArrayObject
{
public function operate($sign)
{
$sign = max(-1, min(1, $sign.'1'));
$arr = $this->getArrayCopy ();
return $arr[0]*(1-$sign) + $sign*array_sum($arr);
}
public function __invoke($sign) {
return $this->operate($sign);
}
}
$arr = new Operands($arr);
echo $arr('-'), ', ' , $arr('+');

<?php echo eval(implode("-", $arr)); ?>

Try this:
$arr = array(1,2,3,4,5);
// load the first number to subtract
$result = $arr[0];
$i = 1;
foreach($arr as $item)
{
if ($i !=1) // skip the first one
$result -= $item;
$i++;
}
echo $result;
?>

This?
<?php
foreach ($arr as $val)
{
$calc -= $val;
}
echo $calc;
?>

Like #mOrSa, but more readable:
<?php
$arr = array(1, 2, 3, 4, 5);
// load the first number to subtract
$result = $arr[0];
for ($i = 1; $i < count($arr); $i++)
{
$result -= $arr[i];
}
echo $result;
?>

Related

How to get array min value

I have multidimensional array and me need to get a minimum value.
Array may be [65,4,4,511,5,[[54,54[.[.[..].].]] and so on.
example code
<?php
$arr = [5, 1 , 2, 3, [1,5,59,47,58,[0,12,562]]];
function NumMin($arr)
{
$num = '';
foreach ($arr as $item => $i) {
if(is_array($i)){
NumMin($i);
}
else{
$num .= $i.',';
}
}
$num .= $num;
return $num;
}
$g = NumMin($arr);
var_dump($g);
I need to get 0
You can use array_walk_recursive() function to flatten a given array (makes it one-dimensional).
And use simply min() function for getting the desired output after.
array_walk_recursive($arr, function($v) use (&$res){
$res[]=$v;
});
echo min($res);
Demo
<?php
$GLOBALS["min"] = 999999; //min value int
$arr = [[[5,6],7],9,7,5, 1 , 2, 3, [1,5,59,47,58,[1,12,562]]];
array_walk_recursive($arr, 'NumMin');
function NumMin($item)
{
if(intval($item) <= intval($GLOBALS["min"]))
{
$GLOBALS["min"] = intval($item);
}
}
// The end, $GLOBALS["min"] will have the least value
echo $GLOBALS["min"];
?>

Getting the first occurrence of modulus eval

Consider this array:
$numbers = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
How can I loop through this array and get the FIRST number and the LAST number where the eval below is true?
foreach($numbers as $number){
if(($number % 2)==0){
//This will execute for the numbers 2,4,6, etc...
//The first occurrence here will be 2 and the last will be 16
}
}
If I got you right you want the min and the max only of even values.
Creating a helper variable should solve this easily.
<?php
$numbers = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
$even = array();
foreach($numbers as $number){
if(($number % 2) == 0){
//This will execute for the numbers 2,4,6, etc...
//The first occurrence here will be 2 and the last will be 16
// Store only even values on the array to access it later using min() and max() functions
$even[] = $number;
}
}
print_r($even);
echo min($even); // prints 2
echo max($even); // prints 16
?>
function getNumber(Array $numbers) {
foreach($numbers as $number) {
if (!($number % 2)) {
return $number;
}
}
}
$numbers = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
$first = getNumber($numbers); // 2
$last = getNumber(array_reverse($numbers)); // 16
$first = null;
$temp = null;
foreach($numbers as $number){
if(($number % 2)==0){
//This will execute for the numbers 2,4,6, etc...
//The first occurrence here will be 2 and the last will be 16
//
$temp = $number;
// Check if the first number has been assigned yet, if not set to $first
if ($first === null) {
$first = $number;
}
}
}
// Retrieve last valid value and set as last
$last = $temp;
Should do the trick
$numbers = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
foreach ($numbers as $number) {
if(0===($number%2))
{
(!isset($first)) ? $first=$number : $last=$number;
$last = $number;
}
}
echo $first.'<br />';
echo $last.'<br />';

How to replace a value in array by another different value in PHP?

I'm trying to find a way to replace any duplicated value but the only solution I have found so far is array_unique which doesn't really work for me as I need the duplicate to be replaced by another number which itself is not a duplicate.
function generate_random_numbers($rows, $delimiter)
{
$numbers = array();
for($i = 0; $i < $delimiter; $i++)
{
$numbers[$i] = rand(1, $rows);
if(in_array($i, $numbers))
{
$numbers[$i] = rand(1, $row);
}
}
return $numbers;
}
$numbers = generate_random_numbers(20, 10);
print_r($numbers);
would anyone help me out on this one please?
You can do this way easier and faster.
Just create an array for all possible numbers with range(). Then shuffle() the array and take an array_slice() as big as you want.
<?php
function generate_random_numbers($max, $amount) {
if($amount > $max)
return [];
$numbers = range(1, $max);
shuffle($numbers);
return array_slice($numbers, 0, $amount);
}
$numbers = generate_random_numbers(20, 10);
print_r($numbers);
?>
And if you want to get 490 unique elements from a range from 1 - 500, 10'000 times:
My version: ~ 0.7 secs
Your version: Order 2 birthday cakes, you will need them.
You are inserting a random number and then, if it is already in the array (which it MUST be because you just inserted it), you use a new random number, which might be a duplicate. So, you have to get a number that is not a duplicate:
do {
$num = rand(1,$rows);
} while(!in_array($num, $numbers));
Now, you know that $num is not in $numbers, so you can insert it:
$numbers[] = $num;
You were pretty close.
The if-clause needs to be a loop, to get new random number.
(Also your in_array was slightly wrong)
function generate_random_numbers($rows, $delimiter) {
$numbers = array();
for($i = 0; $i < $delimiter; $i++) {
do {
$number = rand(1, $rows);
}
while(in_array($number, $numbers));
$numbers[] = $number;
}
return $numbers;
}

Pair the elements in an array by two's then find the difference and sum

Let's say I have this array
$number = [2,1,4,3,6,2];
First pair the elements on an array by two's and find their difference
so this is the output in the first requirement
$diff[] = [1,1,4];
Second sum all the difference
this is the final output
$sum[] = [6];
Conditions:
the array size is always even
the first element in a pair is always greater than the second one, so their is no negative difference
What I've done so far is just counting the size of an array then after that I don't know how to pair them by two's. T_T
Is this possible in php? Is there a built in function to do it?
One line:
$number = [2,1,4,3,6,2];
$total = array_sum(array_map(function ($array) {
return current($array) - next($array);
}, array_chunk($number, 2)));
echo $total;
This should work fine:
<?
$number = array(2,1,4,3,6,2);
for($i=0;$i<count($number); $i+=2){
$dif[] = $number[$i] - $number[$i+1];
}
print_r($dif);
$sum = 0;
foreach ($dif as $item){
$sum += $item;
}
echo 'SUM = '.$sum;
?>
Working CODE
If you want all the different stages kept,
$numbers = [2,1,4,3,6,2];
$diff = [];
for($i=0,$c=count($numbers);$i<$c;$i+=2)
{
$diff[] = $numbers[$i]-$numbers[$i+1];
}
$sum = array_sum($diff);
Else, to just get the total and bypass the diff array:
$numbers = [2,1,4,3,6,2];
$total = 0;
for($i=0,$c=count($numbers);$i<$c;$i+=2)
{
$total += $numbers[$i]-$numbers[$i+1];
}
I have got this far it gives the required solution.
$arr = array(2,1,4,3,6,2);
$temp = 0;
$diff = array();
foreach ($arr as $key => $value) {
if($key % 2 == 0) {
$temp = $value;
}
else {
$diff[] = $temp - $value;
}
}
print_R($diff);
print 'Total :' . array_sum($diff);
Note : Please update if any one knows any pre-defined function than can sorten this code.
Please check and see if this works for you.
<?php
$sum=0;
$number = array(2,1,4,3,6,2);
for ($i=0;$i<=count($number);$i++) {
if ($i%2 == 1 ) {
$sum = $sum + $number[$i-1] - $number[$i];
}
}
print $sum;
?>
Well with your conditions in mind I came to the following
$number = [2,1,4,3,6,2];
$total = 0;
for($i = 0; $i < count($number); $i+=2) {
$total += $number[$i] - $number[$i + 1];
}
Try this one:
$number = array(2,1,4,3,6,2);
$diff = array();
$v3 = 0;
$i=1;
foreach($number as $val){
if ($i % 2 !== 0) {
$v1 = $val;
}
if ($i % 2 === 0) {
$v2 = $val;
$diff[] = $v1-$v2;
$v3+= $v1-$v2;
}
$i++;
}
print $v3;//total value
print_r($diff); //diff value array

finding a specific formula to sort an array in PHP

I was wondering if there were any mathematicians who could help me solve the following problem:
I am trying to turn the sequence of numbers 012345678 into 036147258.
The purpose is to sort the indices of a PHP array where no standard sorting function is viable.
This is as far as I have got:
for($i=0; $i<count($arrayWithNineIndices); $i++)
{
$j=($i%3)*3;
echo $j;
if($i%3===0) echo " <----";
echo "<br />";
}
which outputs 036036036 vertically with markers on the zeros.
Ideally what I need is a mechanism to add one to the values that follow first marker, then two to the values that follow the second.
I have spent all morning trying, mainly with (j=0; j<3; j++) loops, but to no avail.
$result = array();
for ($i = 0; $i < 3; $i++) {
for ($j = $i; isset($array[$j]); $j += 3) {
$result[] = $array[$j];
}
}
print_r($result);
See it working
You can use
$str = "012345678";
list($a, $b, $c) = array_chunk(str_split($str), 3);
foreach ( array_map(null, $a, $b, $c) as $part ) {
echo implode($part);
}
Output
036147258
See Live Demo
For a universal function
echo autoShift("012345678", 3), PHP_EOL;
echo autoShift("0123456", 3), PHP_EOL;
echo autoShift("012345678", 2), PHP_EOL;
echo autoShift("0123", 2), PHP_EOL;
Output
036147258
0361425
024681357
0213
Function Used
function autoShift($str, $shift = 3) {
$args = array_chunk(str_split($str), $shift);
array_unshift($args, null);
return implode(array_map("implode", call_user_func_array("array_map", $args)));
}

Categories