get a set of values from an array - php

i have a set of arrays:
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
what i want to do is to get a set of $data array from each number of $nums array,
the output must be:
output:
2=11,22
3=33,44,55
1=66
what i tried so far is to slice the array and remove the sliced values from an array but i didn't get the correct output.
for ($i=0; $i < count($nums); $i++) {
$a = array_slice($data,0,$nums[$i]);
for ($x=0; $x < $nums[$i]; $x++) {
unset($data[0]);
}
}

Another alternative is to use another flavor array_splice, it basically takes the array based on the offset that you inputted. It already takes care of the unsetting part since it already removes the portion that you selected.
$out = array();
foreach ($nums as $n) {
$remove = array_splice($data, 0, $n);
$out[] = $remove;
echo $n . '=' . implode(',', $remove), "\n";
}
// since nums has 2, 3, 1, what it does is, each iteration, take 2, take 3, take 1
Sample Output
Also you could do an alternative and have no function usage at all. You'd need another loop though, just save / record the last index so that you know where to start the next num extraction:
$last = 0; // recorder
$cnt = count($data);
for ($i = 0; $i < count($nums); $i++) {
$n = $nums[$i];
echo $n . '=';
for ($h = 0; $h < $n; $h++) {
echo $data[$last] . ', ';
$last++;
}
echo "\n";
}

You can array_shift to remove the first element.
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
foreach( $nums as $num ){
$t = array();
for ( $x = $num; $x>0; $x-- ) $t[] = array_shift($data);
echo $num . " = " . implode(",",$t) . "<br />";
}
This will result to:
2 = 11,22
3 = 33,44,55
1 = 66

This is the easiest and the simplest way,
<?php
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
$startingPoint = 0;
echo "output:"."\n";
foreach($nums as $num){
$sliced_array = array_slice($data, $startingPoint, $num);
$startingPoint = $num;
echo $num."=".implode(",", $sliced_array)."\n";
}
?>

Related

Calculate sum in while loop to array

When the number 6 is giving I need to calculate till 6: for example: 1+2+3+4+5+6=21. I also need to add the sums of each to an array like: 1+2=3, 1+2+3=6, 1+2+3+4=10, ...
I have tried to make the while loop to be printed and this working fine but nog for array purpose:
<?php
$number = $_POST['number'];
$i = 1;
$cal = 0;
$tussenBerekening = array();
while ($i <= $number) {
echo $i;
$cal = $cal + $i;
array_push($tussenBerekening, $cal);
if ($i != $number) {
echo " + ";
} else {
echo " = " . $cal;
}
$i++;
}
?>
This is my new code, it prints, but no total sum.
<?php
$number = $_POST['number'];
$i = 2;
$cal = 0;
$sum = 1;
$berekeningen = array();
while ($i <= $number) {
$sum .= "+" . $i;
array_push($berekeningen, $sum);
$i++;
}
print_r($berekeningen);
?>
Here's a solution:
$i = 1;
$number = 6;
while ($i <= $number) {
// generate array with values from 1 to $i
$array = range(1, $i);
// if there're more than 1 element in array - output sum
if (count($array) > 1) {
// 1+2+... part // sum of elements of array
echo implode('+', $array) . ' = ' . array_sum($array) . '<br />';
}
$i++;
}

Get max/min value from json file with PHP

Im am trying to get the min and max temp value from a json src. I'm not getting the desired result that I am looking for. This is what i have so far.
Any help is greatly appreciated
<?php
$url = 'https://samples.openweathermap.org/data/2.5/forecast?id=524901&appid=b6907d289e10d714a6e88b30761fae22';
$data = file_get_contents($url);
$forecasts = json_decode($data);
$length = count($forecasts->list);
for ($i = 0; $i < $length; $i++) {
$val = round($forecasts->list[$i]->main->temp, 0);
}
$min = min($val);
$max = max($val);
echo "max: ". $max ." - min: ". $max;
?>
You are overwriting the value of $val in each pass through your for loop. What you actually want to do is push each value into an array that you can then take the min and max of:
$val = array();
for ($i = 0; $i < $length; $i++) {
$val[] = round($forecasts->list[$i]->main->temp, 0);
}
$min = min($val);
$max = max($val);
Ok so I'm assuming that "temp" is the attribute where you want to get min/max:
<?php
function max($list){
$highest = $list[0]->main->temp;
foreach($list as $l){
$highest = $l->main->temp > $highest ? $l->main->temp : $highest;
}
return $highest;
}
function min($list){
$lowest = $list[0]->main->temp;
foreach($list as $l){
$lowest = $l->main->temp < $lowest ? $l->main->temp : $highest;
}
return $lowest;
}
$url = 'https://samples.openweathermap.org/data/2.5/forecast?id=524901&appid=b6907d289e10d714a6e88b30761fae22';
$data = file_get_contents($url);
$forecasts = json_decode($data);
$length = count($forecasts->list);
$min = min($forecasts->list);
$max = max($forecasts->list);
echo "max: ". $max ." - min: ". $max;
?>
should be copy-pastable for your case...

How to Print Alphabet sequentially in PHP?

I have an array variable $arr = array('A','B','C','D');
$number = 5; (This is dynamic)
My new array value should be
$arr = array('A','B','C','D','E','F','G','H','I');
If
$number = 3;
Output should be:
$arr = array('A','B','C','D','E','F','G');
If $number variable will come more than 22 then print array from A to Z and with AA, AB, AC.. etc.
How to do that in PHP code?
How about this one: https://3v4l.org/IGhoL
<?php
/**
* Increments letter
* #param int $number
* #param array &$arr
*/
function increment($number, &$arr) {
$char = end($arr);
$char++;
for ($i = 0; $i < $number; $i++, $char++) {
$arr[] = $char;
}
}
$arr = range('A', 'D');
$number = 30;
increment($number, $arr);
var_dump($arr);
You can increment letters by incrementing it, then store it that array itself. This will print two letter sequence also ie., AA, AB ...
$arr = array('A','B','C','D');
$item = end($arr) ;
$i = 0 ;
while( $i++ < $number ) {
$arr[] = ++$item ;
}
print_r($arr) ;
Here is example to add chars from alphabet to array with offset. This works for one char. If you wish to work for more chars use loop in loop.
for ($c = ord('A') + $offset ;$c <= ord('Z');$c++) {
Array[] += chr($c);
}
$output = array();
$arr = array(A,B,C,D,E);
$data = range('F','Z');
$num = 4;
if($num < 22){
$output = array_merge($arr,array_slice($data, 0, $num));
}else{
// Write ur format here..
// $output = array('AA','AB',......,'AZ');
}
echo '<pre>';
print_r($output);

How to create random numbers in such a way that sum of the numbers should be only whole number or zero in php?

I am creating one algorithm for kids that will create random numbers and showing 5 numbers in each row upto 6 rows.for whole numbers it is good.But when i am taking random numbers between a negative and a positive number then there is possibility of negative result.So what should i write so that the result will be only positive number or zero irrespective of taking negative numbers? Below is my code,
$Final_Array = array();
$Final_Ansarray = array();
for ($i = 1; $i < 31; $i++) {
$Random_Number = mt_rand(-4,8);
$RandVal = $Random_Number . "";
array_push($Final_Array, $RandVal);
}
$Chunked_Array = array_chunk($Final_Array, 5);
foreach ($Chunked_Array as $key => $value) {
foreach ($value as $key2 => $value2) {
echo $value2 . "\n";
}
echo "|";
}
foreach ($Chunked_Array as $k => $subArray) {
$Answers = array_sum($subArray);
echo $Answers . "|";
array_push($Final_Ansarray, $Answers);
}
Try this
$cols = 5;
$rows = 6;
$array = array();
for ($j = 0; $j < $rows; $j++)
{
do
{
for ($i = 0; $i < $cols; $i++)
$array[$i] = mt_rand(-4, 8);
}
while (array_sum($array) < 0); // pass only non negative sums
echo'sum', json_encode($array), ' = ', array_sum($array), PHP_EOL;
}
Example output
sum[1,-1,2,8,-2] = 8
sum[1,5,5,5,-4] = 12
sum[2,7,-1,6,0] = 14
sum[8,0,-2,-1,0] = 5
sum[7,-2,8,4,2] = 19
sum[7,-4,-4,0,1] = 0

Division with Arrays

<?php
$txtfield = $_POST['number1'];
$arr = explode(' ',trim($txtfield));
$operator = $arr[0];
$count=count($arr);
$sum = array_sum($arr);
echo "Sum of the number:".$sum. "<br>";
$prod=1;
for ($i=1; $i<$count; $i++){
$prod = $prod * $arr[$i];}
echo "Product of the numbers:".$prod."<br>";
$diff=$arr[1];
for ($i=1; $i<$count; $i++){
$diff= $diff - $arr[$i+1];
}
echo "Difference of the numbers:".$diff."<br>";
$div=$arr[1];
foreach ($i=1; $i<$count; $i++){
$div=$div / $arr[$i];
}
echo "Qoutient of the numbers:". $div. "<br>";
?>
This line of code doesn't seem to work properly. When I entered 10 & 5 the output is:
Sum of the number:15
Product of the numbers:50
Difference of the numbers:5
Qoutient of the numbers:0.2
Assuming that by I entered 10 & 5 you mean that $arr looks like this:
$arr = array(
1 => 10,
2 => 5
);
...then 0.2 is the expected result of the quotient. This is what your code does:
$div = 10;
$div = 10 / 10; // 1
$div = 1 / 5; // 0.2
I think that you meant to initialise $i at 2. This will give your expected output. But a better approach would be this:
$arr = array(
10,
5
);
// Make a copy of $arr before this if you need the original data intact
$quotient = array_shift($arr);
foreach ($arr as $val) {
$quotient /= $val;
}
Now the element indexes are irrelevant, only the element order is significant.
EDIT
Here is how I would write your newly posted full code:
// Split on any number of whitespace characters to avoid bad user input
$arr = preg_split('/\s+/', $_POST['number1']);
// Remove the first element of the array so it doesn't interfere with calculations
$operator = array_shift($arr);
// This is fine
$sum = array_sum($arr);
// Product has a function of it's own
$prod = array_product($arr);
// Difference and quotient can be done in one loop
$diff = $quot = array_shift($arr);
foreach ($arr as $val) {
$diff -= $val;
$quot \= $val;
}
// Echo the results
echo "Sum of the number:".$sum."<br>";
echo "Product of the numbers:".$prod."<br>";
echo "Difference of the numbers:".$diff."<br>";
echo "Qoutient of the numbers:".$quot."<br>";
I've reformatted your program and added static values so that it will execute standalone.
<?php
$arr = array(10, 5);
$count = count($arr);
$sum = array_sum($arr);
echo 'Sum of the number: '.$sum."<br>\n";
$prod = 1;
for($i = 0; $i < $count; $i++)
{
$prod *= $arr[$i];
}
echo 'Product of the numbers: '.$prod."<br>\n";
$diff = $arr[0];
for($i = 1; $i < $count; $i++)
{
$diff -= $arr[$i];
}
echo 'Difference of the numbers: '.$diff."<br>\n";
$div = $arr[0];
for($i = 1; $i < $count; $i++)
{
$div /= $arr[$i];
}
echo 'Quotient of the numbers: '.$div."<br>\n";
?>
The output of this program is:
Sum of the number: 15
Product of the numbers: 50
Difference of the numbers: 5
Quotient of the numbers: 2

Categories