eloquent how to add all values of an array - php

for example i have the following codes in my controller:
foreach($-request->input('text') as $var){
$sum[] = $var;
}
$last = sizeof($request->input('text'));
$i = 0;
while($i < $last)
{
//insert code here
$i++;
}
$request->input('text') has the following values:
['1,2,3,4,5']
how do you add the values in the variable $var[] in eloquent? i tried the sum but it didn't work. someone also said ill use += sign on my increment

explode to convert comma-separated numbers into an array.
intval on all array elements using array_map to cast them into integer.
array_sum to add them all.
Try this.
$array = $request->input('text'); // ['1, 2, 3, 4, 5'];
$string_numbers = explode(', ', $array[0]); // ['1', '2', '3', '4', '5']
$numbers = array_map('intval', $string_numbers); // [1, 2, 3, 4, 5]
echo array_sum($numbers); // 15

$num = ['1,2,3,4,5']; // when $n = $request->input('text');
$numbers = explode(',', $num[0]);
$sum = array_sum($numbers);
dd($sum);
I think this will be helpful to you

Related

How to return value of an array inside a loop and use it outside in PHP

I have a code like this:
Lets assume that this arrays has this values:
$arr1 = array();
$arr2 = array();
$result = array();
$arr1[] = array( 'grade' => [1,2,3,4] );
$arr2[] = array( 'grade' => [1,2,3,4] );
foreach($arr1 as $a1){
$set1 = $a1['grade'];
foreach($arr2 as $a2){
$set2 = $a2['grade'];
}
$result[] = array('show_result' => $set1+$set2);
}
foreach{$result as $res){
echo $res['show_result'];
}
The output of the array $res['show_result'] must be:
2, 4, 6, 8
But I get the wrong addition of this arrays. Help will be much appreciated.
As Joni said, your first error is on line 3: ' should be ;
Then, you're not filling arrays like you wanted : array( 'grade' => 1,2,3,4 ); creates an array with first key is 'grade' with value '1', then second key is '0' with value '2' etc...
Your last foreach loop has a syntax error similar to your first error.
See a working correction here
$arr1 = array();
$arr2 = array();
$result = array();
array_push($arr1, 1, 2, 3, 4); //fill array with 4 values (integers)
array_push($arr2, 1, 2, 3, 4); //fill array with 4 values (integers)
//so $arr1 & $arr2 are now a 4 elements arrays
$length = count($arr1); //size of array, here 4
for ($i = 0; $i < $length; $i++) { //loop over arrays
array_push($result, ($arr1[$i] + $arr2[$i])); //fill the results array with sum of the values from the same position
}
var_dump($result);
You have quite a few syntax errors in your code.
Although this solution works, the idea behind using the same counter, $i, to extract a value from both arrays is brittle. For example, you'll get an Undefined offset if the first array has 5 grades instead of 4. If you take a step back and explain your problem in the larger context, perhaps we can provide a better solution. I get the sneaking suspicion you're asking an XY Problem.
http://sandbox.onlinephpfunctions.com/code/bb4f492c183fcde1cf4edd50de7ceebf19fe343a
<?php
$gradeList1 = ['grade' => [1,2,3,4]];
$gradeList2 = ['grade' => [1,2,3,4]];
$result = [];
for ($i = 0; $i < count($gradeList1['grade']); $i++) {
$first = $gradeList1['grade'][$i];
$second = $gradeList2['grade'][$i];
$result['show_result'][] = (int)$first + (int)$second;
}
var_dump($result);

Keep unique node with lowest value on second index

I am working on a multi dimensional array in PHP. How is it possible to select unique values from 0 index of a nested array which has lowest value on index 1?
Below is my sample data array
$data = array (
array(1, 9),
array(1, 3),
array(1, 5),
array(9, 2),
array(9, 7),
);
I am trying to get following array as a result
$result = array (
array(1, 3),
array(9, 2),
);
One way to do this could be to loop the array, use the indexes of the arrays and compare the second value. If the stored second value is greater than the new value, then overwrite it.
$data = array (
array(1, 9),
array(1, 3),
array(1, 5),
array(9, 2),
array(9, 7),
);
$result = [];
foreach ($data as $d) {
if (!isset($result[$d[0]])) {
$result[$d[0]] = $d;
continue;
}
if ($result[$d[0]][1] > $d[1]) {
$result[$d[0]] = $d;
}
}
print_r($result);
Demo
$data = array (
array(1, 9),
array(1, 3),
array(1, 5),
array(9, 2),
array(9, 7),
);
$result = [];
$lowest0 = null;
$lowest1 = null;
foreach($data as $row){
if($lowest0 === null || $row[0] < $lowest0[0] || ($row[0] === $lowest0[0] && $row[1] < $lowest0[1]))
{
$lowest0 = $row;
}
if($lowest1 === null || $row[1] < $lowest1[1] || ($row[1] === $lowest1[1] && $row[0] < $lowest0[0]))
{
$lowest1 = $row;
}
}
$result = [$lowest0,$lowest1];
var_dump($result);
Short and dirty:
$data = array (
array(1, 9),
array(1, 3),
array(1, 5),
array(9, 2),
array(9, 7),
);
foreach ($data as $row) {
($row[1] < ($uniq[$row[0]][1] ?? INF)) and $uniq[$row[0]] = $row;
}
var_dump($uniq);
Pass resulting array through array_values if re-indexing from 0 is important to you
This is as clear as mud, but it I made it as an example that it works without looping.
In short I use min and array_intersect(_key) to find where the minimum values are in the columns (with array_column).
//split out the two columns
$col0 = array_column($data, 0);
$col1 = array_column($data, 1);
// find minimum value in each
$min0 = min($col0);
$min1 = min($col1);
// find what keys this minimum value is in of each array
$mincol0 = array_intersect($col0, [$min0]);
$mincol1 = array_intersect($col1, [$min1]);
// use the previous and compare with minimum value of the other column
$result[] = $data[array_keys(array_intersect_key($col1, $mincol0),min(array_intersect_key($col1, $mincol0)))[0]];
$result[] = $data[array_keys(array_intersect_key($col0, $mincol1),min(array_intersect_key($col0, $mincol1)))[0]];
Var_dump($result);
https://3v4l.org/dgbDK
Since I apperantly missunderstood the question.
Here is another answer, still no need to loop the full array. That is just a waste of time.
Loop only unique column 0 values and find the minmum value in column 1 using array_intersect and array_intersect_key.
$col0 = array_column($data, 0);
foreach(array_unique($col0) as $item){
$intersect = array_intersect($col0, [$item]);
$res[] = min(array_intersect_key($data, $intersect));
}
var_dump($res);
https://3v4l.org/3UPQh

Receive values from array between other values

I have array, for example:
$array = (5, 2, 17, 9, 12, 6);
and always two values - $first and $last. I would like get all values from $array between $first and $last.
For example:
$first = 2;
$last = 6;
I would like receive:
$receive = array(17, 9, 12);
For example:
$first = 5;
$last = 9;
I would like receive:
$receive = array(2, 17);
How is the best way for that?
Search and slice:
$receive = array_slice($array,
$s=array_search($first, $array)+1,
array_search($last, $array)-$s);

PHP Script and max() Value

Sorry for my bad English and thanks for your help in advance! I have kind of a tricky problem I've encountered while coding. Here's the point:
I need a script that essentially extracts the 5 max values of 5 arrays, that are "mixed", i.e. they contain "recurrent" values. Here is an example:
array1(a, b)
array2(a, c, d, e, g)
array3(b, d, g, h)
array4(e, t, z)
array5(b, c, d, k)
The 2 essential requests are:
1) the sum of those 5 arrays (array1+array2+array3...) MUST be the highest possible...
2) ...without repeat ANY value previously used** (e.g. if in array1 the top value was "b", this cannot be re-used as max value in arrays 3 or 5).
Currently I have this...:
$group1 = array(a, b);
$group = array(a, b, c, d);
$max1a = max(group1);
$max2a = max(group2) unset($max1a);
$sum1 = $max1a + $max2a;
$max2b = max(group2);
$max1b = max(group1)
unset($max2b);
$sum2 = $max1b + $max2b;
if($sum1 > $sum2) {
echo $sum1
} else {
echo $sum2
}
... but it's kinda impossible to use this code with 5 arrays, because I should compare 5! (120...!!!) combinations in order to find the max sum value.
I know the problem is quite difficult to explain and to solve, but I really need your help and I hope you can save me!!!
Cheers
I'm adding this as another answer to leave the previous one intact for someone coming across this looking for that variation on this behaviour.
Given the 2 arrays:
$array1 = array(30, 29, 20);
$array2 = array(30, 20, 10);
The maximum sum using one element from each is 59 - this is dramatically different to my previous approach (and the answers' of others) which took the max element of the first array and then the highest element of the next array that is not equal to any previously used value - this would give 50 instead.
The code you want is this:
$mainArray = array();
$mainArray[] = array(30, 29, 20);
$mainArray[] = array(30, 20, 10);
$tempArray = array();
$newArray = array();
foreach($mainArray as $innerArray) {
$newArray = array();
if (count($tempArray) == 0) {
foreach ($innerArray as $value) {
$newArray[] = array('total' => $value, 'used' => array($value));
}
}
else {
foreach ($tempArray as $key => $innerTempArray) {
$placed = FALSE;
foreach ($innerArray as $value) {
if (!(in_array($value, $innerTempArray['used']))) {
$newArray[] = array('total' => $tempArray[$key]['total'] + $value, 'used' => $tempArray[$key]['used']);
$newArray[count($newArray) - 1]['used'][] = $value;
$placed = TRUE;
}
}
if (!($placed)) {
echo "An array had no elements that had not already been used";
die();
}
}
}
$tempArray = $newArray;
}
$total = 0;
if (count($newArray) == 0) {
echo "No data passed";
die();
}
else {
$total = $newArray[0]['total'];
}
for ($i = 0; $i < count($newArray); $i++) {
if ($newArray[$i]['total'] > $total) {
$total = $newArray[$i]['total'];
}
}
var_dump($total);
EDIT - Do not repeat used variables (but repeated values are ok):
Let
//$a = 30, $b = 30, $c = 25, $d = 20, $e = 19
$array1 = array($a, $c, $d);
$array2 = array($b, $d, $e);
We want to choose $a from $array1 and $b from $array2 as these give the largest sum - although they're values are the same that is allowed because we only care if the names of the variables saved to that place are the same.
With the arrays in the above format there is no way of achieving the desired behaviour - the arrays do not know what the name of the variable who's value was assigned to their elements, only it's value. Therefore we must change the first part of the original answer to:
$mainArray[] = array('a', 'c', 'd');
$mainArray[] = array('b', 'd', 'e');
and also have either the of the following before the first foreach loop (to declare $a, $b, $c, $d, $e)
//either
extract(array(
'a' => 30,
'b' => 30,
'c' => 25,
'd' => 20,
'e' => 19
));
//or
$a = 30; $b = 30; $c = 25; $d = 20; $e = 19;
The above both do exactly the same thing, I just prefer the first for neatness.
Then replace the line below
$newArray[] = array('total' => $value, 'used' => array($value));
with
$newArray[] = array('total' => ${$value}, 'used' => array($value));
The change is curly brackets around the first $value because that is then evaluated to get the variable name to use (like below example):
$test = 'hello';
$var = 'test';
echo ${$var}; //prints 'hello'
A similar change replaces
$newArray[] = array('total' => $tempArray[$key]['total'] + $value, 'used' => $tempArray[$key]['used']);
with
$newArray[] = array('total' => $tempArray[$key]['total'] + ${$value}, 'used' => $tempArray[$key]['used']);
Now the code will function as wanted :)
If you are dynamically building the arrays you are comparing and can't build the array of strings instead of variables then there is no way to do it. You would need some way of extracting "$a" or "a" from $a = 30, which PHP is not meant to do (there are hacks but they are complicated and only work in certain situations (google "get variable name as string in php" to see what I mean)
If by the top value you mean the first alphabetically then the following would work:
$array1 = array('a', 'b');
$array2 = array('a', 'c', 'd', 'e', 'g');
$array3 = array('b', 'd', 'g', 'h');
$array4 = array('e', 't', 'z');
$array5 = array('b', 'c', 'd', 'k');
$mainArray = array($array1, $array2, $array3, $array4, $array5);
foreach ($mainArray as $key => $value) {
sort($mainArray[$key]);
}
$resultArray = array();
foreach($maniArray as $key1 => $value1) {
$placed = FALSE;
foreach ($value1 as $value2) {
if (!(in_array($value2, $resultArray))) {
$resultArray[] = $value2;
$placed = TRUE;
break;
}
}
if (!($placed)) {
echo "All the values in the " . ($key + 1) . "th array are already max values in other arrays";
die();
}
}
var_dump($resultArray);
I'm not sure, of i really understood your problem correctly, these are my assumptions:
You have five arrays containing numbers
These numbers can occur multiple times across the arrays
You want to find the highest possible sum of elements across your arrays
The sum uses one single value of each array
But the sum must not use the same number twice
Is that correct?
If Yes, then:
The highest possible sum across all arrays is always the sum of the largest elements. If you do not want to use the same number twice, you can just get the maximum from the first array, remove it from all the others and then sum up all the remaining maxima.
Like so:
$arrays = array();
$arrays[] = array(1, 2);
$arrays[] = array(1, 3, 4, 5, 7);
$arrays[] = array(2, 4, 7, 8);
$arrays[] = array(5, 20, 26);
$arrays[] = array(2, 3, 4, 11);
for($i=0, $n=count($arrays); $i<$n; $i++) {
if($i===0) {
$a1max = max($arrays[$i]);
$sum = $a1max;
} else {
$duplicate_pos = array_search($a1max, $arrays[$i]);
if($duplicate_pos !== FALSE) {
unset($arrays[$i][$duplicate_pos]);
}
$sum += max($arrays[$i]);
}
}
echo "sum: " . $sum . "\n";
Assuming you have grouped together all your values in one array like this,
$array = array(
array(1,2,3),
array(1,2,3,4),
array(1,2,3,4,5,6),
array(1,2,3,4,5,6),
array(1,2,3,4,5,6,7)
);
Loop through $array, and get the highest value which has not been used previously,
$max = array();
foreach($array as $value)
$max[] = max(array_diff($value, $max));
Calculate the sum of all values with array_sum(),
echo "The maximal sum is: ".array_sum($max);

Merge 2 arrays in CakePHP

I have two arrays array1 and array2. I want to merge these two arrays into one and show the values of merged array in a dropdown. I want the values in a way that the value of first array - value of 2nd array.
e.g:
$employeePlaces1 = array(1, 2, 4,9);
$employeePlaces2 = array(3, 5, 6,7);
I want in dropdown the value as $employeePlaces1[0]-$employeePlaces2[1],
$employeePlaces1[0]-$employeePlaces2[1].
1-3,
2-5,
4-6,
9-7.
How can I do this ?
$employee1 = array(1, 2, 4, 9);
$employee2 = array(3, 5, 6, 7);
function doMerge($n, $m) {
return $n.'-'.$m;
}
$c = array_map("doMerge", $employee1, $employee2);
print_r($c);
Or in PHP 5.3 syntax with lambda style functions:
$c = array_map(function($n, $m) {return $n.'-'.$m;}, $employee1, $employee2);
You can use the array_diff function
http://www.php.net/manual/en/function.array-diff.php
Answer for the edited question
//assuming both the arrays have the same length
echo "<select>";
for($i=0;$i<count($employeePlaces1);$i++)
{
echo "<option>".$employeePlaces1[i]." - ".$employeePlaces2[i]."</option>";
}
echo "</select>";
How about using array_combine?
http://www.php.net/manual/en/function.array-combine.php
Here is how you could manually loop through them and match the values together.
$list = array();
for($i=0; $i<=count($employeePlaces1); $i++) {
$list[] = $employeePlaces1[$i].'-'.$employeePlaces2[$i];
}
Haven't tested, but should be the gist of what you need.
Why not just loop over the arrays, i.e. do it longhand. Then you can get on with something else!
Edit in response to comment 1:
CakePHP is expecting:
<?php echo $this->Form->input('field', array('options' => array(
'Value 1'=>'Label 1',
'Value 2'=>'Label 2',
'Value 3'=>'Label 3'
))); ?>
so something like (pseudocode):
resultsArray = array();
loop
resultsArray[i] = inputArray_1[i]-inputArray_2[i];
endloop
in PHP (assumes size of array1 <= size of array2):
for($i=0;$i<count($inputArray_1);$i++)
{
$resultsArr[$i] = $inputArray_1[$i]-$inputArray_2[$i];
}

Categories