I have a loop which i made like this:
$arr = array(1, 2, 3, 4, 5, 6, 7);
foreach ($arr as &$value) {
echo $value;
}
My loop result shows this:
1234567
I would like this to only show the numbers 1 to 4.
And when it reaches 4 it should add a break and continue with 5671.
So an example is:
1234<br>
5671<br>
2345<br>
6712<br>
I have to make this but I have no idea where to start, all hints/tips are very welcome or comment any direction I should Google.
Here is more universal function- you can pass an array as argument, and amount of elements you want to display.
<?php
$array = array(1,2,3,4,5,6,7);
function getFirstValues(&$array, $amount){
for($i=0; $i<$amount; $i++){
echo $array[0];
array_push($array, array_shift($array));
}
echo "<br />";
}
getFirstValues($array, 4);
getFirstValues($array, 4);
getFirstValues($array, 4);
getFirstValues($array, 4);
?>
The result is:
1234
5671
2345
6712
This produces the exact results you want
$arr = array(1, 2, 3, 4, 5, 6, 7);
$k=0;
for($i=1;$i<=5;++$i){
foreach ($arr as &$value) {
++$k;
echo $value;
if($k %4 == 0) {
echo '<br />';
$k=0;
}
}
}
You are looking for array_chunk()
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
$chunks = array_chunk($arr, 4);
foreach ($chunks as $array) {
foreach ($array as $value) {
echo $value;
}
echo "<br />";
}
The output is:
1234
5678
9101112
13
Related
I need to add an item every 6th position.
So it would look like this:
[
//item1
//item2
//item3
//item4
//item5
//NEW ITEM HERE
//item7
//item8
//item9
//item10
//item11
//NEW ITEM
]
I already tried this:
foreach($ports as $key => $port)
{
if($key %9 == 2) {
$ports->splice($key, 0, [$ads]);
}
}
But that's not working any idea?
Use array_chunk and add element to each of sub-arrays:
$portsChunks = array_chunk($ports, 5); // Split array to sub-arrays of max-5 elements.
// Add new element if chunk is full length.
// Means last one will not receive new element if it's shorter than 5
array_walk($portsChunks, function (&$array) {
if (count($array) == 5) {
$array[] = 'New Item';
}
});
// Use arguments unpacking to pass all chunks to array_merge
$ports = array_merge(...$portsChunk);
Example
You can use foreach loop:
$ports = range(1,50);
$new_ports = [];
foreach ($ports as $key => $port) {
$new_ports[] = $port;
if(!(($key+1)%5))
$new_ports[] = 'New item';
}
print_r($new_ports);
$ports = [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6];
$ports = array_chunk($ports, 5);
foreach ($ports as &$port){
array_push($port, 'new value');
}
unset($port);
if(count($ports[count($ports)-1]) < 6){
array_pop($ports[count($ports)-1]);
}
$ports = array_merge(...$ports);
you just need a new array to hold all of your data. and then you iterate over your old array and after each 5th position insert a new element. something like this
$result = [];
$ports = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
$porstCount = count($ports);
for ($i = 0; $i < $portsCount; $i++) {
$result[] = $ports[$i];
if ($i > 0 && $i % 5 === 0) {
$result[] = 'new element';
}
}
// $result will be [1, 2, 3, 4, 5, 'new element', 6, 7, 8, 9, 10, 'new element', 11, 12]
I hope below case solves your problem:
$newarr = array();
$cnt = 1;
foreach($arr as $key=>$value){
$newarr[] = $value;
if($cnt%5 == 0){
$newarr[] = 'this is new item';
}
$cnt++;
}
print_r($newarr);
My task is to create a loop that displays all even numbers in a column and it also displays a sum of all odd numbers in an array.
So far I have made this:
<?php
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
foreach ($numbers as $index=>$value) {
if ($value % 2 == 0)
echo "$value <br>";
}
?>
This code successfully displays a list of all even numbers. However, I still have to include a sum of all odd numbers that is displayed below the list of evens. For some reason, I am supposed to use a variable $sumOdd = 0.
How do I approach this from here on?
<?php
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$sumOdd = 0;
foreach ($numbers as $index=>$value) {
if ($value % 2 == 0)
echo "$value <br>";
} else {
$sumOdd += $value
}
}
echo $sumOdd;
To do it backwards: add all numbers, take out the even ones
<?php
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$sum = array_sum($numbers);
foreach ($numbers as $index=>$value) {
if ($value % 2 == 0)
echo "$value <br>";
$sum = $sum - $value;
}
echo 'odds: '. $sum;
?>
heyo,
the $sumOdd = 0; should be before the foreach, inside the foreach you will do another check and if it's odd you add the number on $sumOdd += $value
this is a short and cleaner answer :
$sumOdd = 0;
foreach (range(1, 10) as $number) {
if (0 === $number % 2) {
echo $number . '<br>';
continue;
}
$sumOdd += $number;
}
echo '<br> sumOdd = '.$sumOdd;
A better way to calculate the sum is to pass the result of array_filter to array_sum. By doing that, you separate the tasks (calculate, display) and the code becomes more clean and maintainable.
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$sumOdd = array_sum(array_filter($numbers, function($v) {
return $v % 2 !== 0;
}));
I am calculating and getting result and array from a function in a foreach loop and do min() or max() on that result but the result is wrong. Can someone explain to me why? Thanks
function subtract($a, $b){
$c=$b-$a;
return $c. ',';
}
$r=3;
$numbers = array(12, 11, 6, 9, 15);
foreach ($numbers as $index=>$value) {
$deductions[]=array(subtract($r, $value));
$minimum=min($deductions);
}
print_r($minimum);
I get 12 instead of 3 in this case.
function subtract($a, $b){
$c=$b-$a;
return $c;
}
$r=3;
$numbers = array(12, 11, 6, 9, 15);
foreach ($numbers as $index=>$value) {
$deductions[]=array(subtract($r, $value));
$minimum=min($deductions);
}
echo min($minimum);
You can use array_walk as Rizier123 already showed the way along with the array_map
$r=3;
$numbers = array(12, 11, 6, 9, 15);
array_walk($numbers,function($v,$k) use(&$result,$r){ $result[$k] = $v-$r;});
print_r(min($result));
I was just going through these questions for PHP and got stuck at one of them. The question is:
You have a PHP 1 dimensional array. Please write a PHP function that
takes 1 array as its parameter and returns an array. The function must
delete values in the input array that shows up 3 times or more?
For example, if you give the function
array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9)the function will returnarray(1, 3, 5, 2, 3, 1, 9)
I was able to check if they are repeating themselves but I apply it to the array I am getting as input.
function removeDuplicate($array){
$result = array_count_values( $array );
$values = implode(" ", array_values($result));
echo $values . "<br>";
}
$qArray = array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9);
removeDuplicate($qArray);
One more thing, we cannot use array_unique because it includes the value which is repeated and in question we totally remove them from the current array.
Assuming the value may not appear 3+ times anywhere in the array:
$array = array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9);
// create array indexed by the numbers to remove
$remove = array_filter(array_count_values($array), function($value) {
return $value >= 3;
});
// filter the original array
$results = array_values(array_filter($array, function($value) use ($remove) {
return !array_key_exists($value, $remove);
}));
If values may not appear 3+ times consecutively:
$results = [];
for ($i = 0, $n = count($array); $i != $n;) {
$p = $i++;
// find repeated characters
while ($i != $n && $array[$p] === $array[$i]) {
++$i;
}
if ($i - $p < 3) {
// add to results
$results += array_fill(count($results), $i - $p, $array[$p]);
}
}
This should work :
function removeDuplicate($array) {
foreach ($array as $key => $val) {
$new[$val] ++;
if ($new[$val] >= 3)
unset($array[$key]);
}
return $array;
}
run this function i hope this help..
function removeDuplicate($array){
$result = array_count_values( $array );
$dub = array();
$answer = array();
foreach($result as $key => $val) {
if($val >= 3) {
$dub[] = $key;
}
}
foreach($array as $val) {
if(!in_array($val, $dub)) {
$answer[] = $val;
}
}
return $answer;
}
You can use this function with any number of occurrences you want - by default 3
function removeDuplicate($arr, $x = 3){
$new = $rem = array();
foreach($arr as $val) {
$new[$val]++;
if($new[$val]>=$x){
$rem[$val]=$new[$val];
}
}
$new = array_keys(array_diff_key($new, $rem));
return $new;
}
I think it is getting correct output. just try once.
$array=array(1,2,3,7,4,4,3,5,5,6,7);
$count=count($array);
$k=array();
for($i=0;$i<=$count;$i++)
{
if(!in_array($array[$i],$k))
{
$k[]=$array[$i];
}
}
array_pop($k);
print_r($k);
in this first $k is an empty array,after that we are inserting values into $k.
You should use array_unique funciton.
<?php
$q = array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9);
print_r(array_unique($q));
?>
Try it and let me know if it worked.
I am trying to interchange the display order in a loop.
For example i have an array $array with values: 1,2,3,4,5 and want to display the result in the order 2,1,3,4,5.
I am using the following code for the purpose and which worked for me:
<?php
$array = array(
1,
2,
3,
4,
5,
);
$tempArray = array();
$count = 1;
foreach($array as $key => $value){
$tempArray[$key] = $value;
if(in_array($count, array(1, 2))){
if($count == 2){
echo $tempArray[1] . '<br />';
echo $tempArray[0] . '<br />';
}
}else{
echo $value . '<br />';
}
$count++;
}
But i would like to know if there is any effective (better) way of doing so?
EDIT:
$array = array(
1,
2,
3,
4,
5,
);
//Either
/*$temp = $array[1];
$array[1] = $array[0];
$array[0] = $temp;*/
//OR
list($array[1], $array[0]) = array($array[0], $array[1]);
foreach($array as $key => $value){
echo $value . '<br />';
}
Either way works fine with minimum code.
Thank you guys!
To change the display order of $array that is array(1, 2, 3, 4, 5) without changing the order of the elements in $array you need to define the display order and then display based on the display order:
$array = array(1, 2, 3, 4, 5);
$display = array_keys($array);
list($display[1], $display[0]) = array($display[0], $display[1]);
foreach ($display as $key)
{
$value = $array[$key];
printf("%d<br />\n", $value);
}
This works - as you wrote it already yourself in the comments - by switching the order (keys) of the first two elements(0 and 1, arrays are zero-based).