PHP first 3 then break and continue again? - php

I'm trying to sort everything out using array & loops
lets say this is an array,
$arr = array('One','Two','Three','Four','Five','Six');
i want to select first three of them to be used as
$arr[0], $arr[1] and $arr[2]
this ends up with one,two,three
i want to use the same for next 3..
something to break it and use the same 0 1 2 index again to return second three
here's an example to explain more,
$arr = array('One','Two','Three','Four','Five','Six');
echo $arr[0].$arr[1].$arr[2]; // OneTwoThree
break; // < ??
echo $arr[0].$arr[1].$arr[2]; // FourFiveSix
also, i want to use it with foreach loop
$arr = array('One','Two','Three','Four','Five','Six');
foreach($arr as $num){
echo $num; // OneTwoThree
if($something == 3){ // < ??
break; // < ??
}
echo $num; // FourFiveSix
}
and what im trying to do is using each three arrays of the array to use them later

Use array_chunk and loop over the result:
foreach(array_chunk($arr, 3) as $a) {
echo $a[0], $a[1], $a[2];
}
Here it is with added linebreaks:
foreach(array_chunk($arr, 3) as $a) {
echo $a[0], $a[1], $a[2], "<br>\n";
}
Note: The last element may have less than three elements! A possible fix for this is to use implode to concatenate the elements:
foreach(array_chunk($arr, 3) as $a) {
echo implode('', $a), "<br>\n";
}

Edit: array_chunk() is a lot more sensible...early mornings
<?php
$arr = array('One','Two','Three','Four','Five','Six');
for($i = 0, $i < count($arr); ++$i)
{
if( ! ($i + 1) % 3)
{
continue;
}
echo $arr[$i - 2] . $arr[$i - 1] . $arr[$i]
}

Related

I have 6 values in array but when I execute, only 4 values are showed. why?

I have 6 values in array $arr1 but when I execute the code, only 4 values are shown, why?
The code finds that the maximum value is 526, but where I use echo to list the whole array the 526-valued array is not shown.
Here is the code:
<?php
$arr1[0][ ]=110;
$arr1[0][ ]=20;
$arr1[0][ ]=526;
$arr1[1][ ]=105;
$arr1[1][ ]=56;
$arr1[1][ ]=96;
echo "The given array is : <br>";
for($i=0;$i=count($arr1);$i++)
{
for($j=0;$j=count($arr1);$j++)
{
Echo "\$arr1[$i][$j] =",$arr1[$i][$j],"<br>";
}
}
$b=0;
foreach($arr1 as $val)
{
foreach($val as $key=>$val1)
{
$b=$val1;
}
}
Echo "The maximum value in the array is =",$b;
?>
There are a few issues with your code example.
The array $arr1 has 2 entries with keys 0 and 1 so if you loop 2 times 2 values, you get 4 values instead of 6.
Then per key, there are 3 entries, so for the second loop you have to use count($arr1[$i]) using [$i] to count the entries for that key.
In the loops, you are setting the value of $i to the count causing an infinite loop $i=count($arr1) while you have to use a < sign instead.
In the second part finding the largest value, you have to first check if the new value is greater than the current value, or else you will always have the last value.
$arr1[0][] = 110;
$arr1[0][] = 20;
$arr1[0][] = 526;
$arr1[1][] = 105;
$arr1[1][] = 56;
$arr1[1][] = 96;
echo "The given array is : <br>";
for ($i = 0; $i < count($arr1); $i++) {
for ($j = 0; $j < count($arr1[$i]); $j++) {
echo "\$arr1[$i][$j] =", $arr1[$i][$j], "<br>";
}
}
$b = 0;
foreach ($arr1 as $val) {
foreach ($val as $key => $val1) {
if ($val1 > $b)
$b = $val1;
}
}
echo "The maximum value in the array is =", $b;
Output
The given array is :
$arr1[0][0] =110
$arr1[0][1] =20
$arr1[0][2] =526
$arr1[1][0] =105
$arr1[1][1] =56
$arr1[1][2] =96
The maximum value in the array is =526
See a Php demo
As #Nick points out, you could also compute the max in the nested for loops directly:
$b = 0;
echo "The given array is :" . PHP_EOL;
for ($i = 0; $i < count($arr1); $i++) {
for ($j = 0; $j < count($arr1[$i]); $j++) {
if ($arr1[$i][$j] > $b) $b = $arr1[$i][$j];
echo "\$arr1[$i][$j] =", $arr1[$i][$j] . PHP_EOL;
}
}
Php demo
You can flatten the array by using splat operator then use max.
echo max(array_merge(...$arr1));
If you want you can use implode to print the values
echo implode(' ',array_merge(...$arr1));
DEMO :- https://3v4l.org/0ZamG
Please use this code. I hope it will works for you.
$arr1[0][ ]=110;
$arr1[0][ ]=20;
$arr1[0][ ]=526;
$arr1[1][ ]=105;
$arr1[1][ ]=56;
$arr1[1][ ]=96;
echo "The given array is : <br>";
for($i=0;$i<count($arr1);$i++)
{
for($j=0;$j<count($arr1);$j++)
{
echo "$arr1[$i][$j] =",$arr1[$i][$j],"<br>";
}
}
$b=0;
sort($arr1);
foreach($arr1 as $val)
{
foreach($val as $key=>$val1)
{
$b=$val1;
}
}
echo "The maximum value in the array is =",$b;

loop error in php code

Here is my code, and it is not removing $arr[5] element so that I am trying to remove strings starting with # from my array
this is code
<?php
$arr = [
'#EXTM3U',
'#EXTINF:177,Paul Dateh & Oren Yoel - Be More',
'Be More.mp3',
'#EXTINF:291,Christopher Toy - Just Because',
'Just Because.mp3',
'#EXTINF:238,Magnetic North - Drift Away',
'Drift Away.mp3'
];
for ($i = 0; $i <= count($arr); $i++) {
if ($arr[$i]{0} == '#') {
echo $arr[$i] . "\n";
unset($arr[$i]);
}
}
print_r($arr);
?>
Reason:- You are counting array length inside the loop and every time when any value got unset() from the array, length of array decreased and value of count($array) changed (simply decreased)
So logically your 5th and 6th element never goes through if condition (they never get traversed by loop because of decreasing length of the array )
Solution 1:- Put count outside and it will work properly:-
$count = count($arr);
//loop start from 0 so use < only otherwise, sometime you will get an undefined index error
for ($i = 0; $i < $count; $i++) {
if ($arr[$i]{0} == '#') {
//echo $arr[$i] . "\n";
unset($arr[$i]);
}
}
print_r($arr);
Output:-https://eval.in/996494
Solution 2:- That's why i prefer foreach() over for() loop
foreach($arr as $key=> $ar){
if ($ar[0] == '#') {
unset($arr[$key]);
}
}
print_r($arr);
Output:-https://eval.in/996502
more spacific :
for ($i = 0; $i < count($arr); $i++) {
if (strpos($arr[$i], '#') !== false) {
echo "<br/>";
} else {
echo $arr[$i]."<br/>";
}
}
Try to use additional array to push right values. You calc count($arr); each iteration and when you do count($arr); your array gets smaller and count($arr); returns smaller values, so last elements won't be comparing, try to use variable to calc count before loop make changes:
<?php
//...
$start_count = count($arr);
for ($i = 0; $i <= $start_count; $i++) {
if ($arr[$i]{0} == '#') {
echo $arr[$i] . "\n";
unset($arr[$i]);
}
}
Or remove bad element with a help of additional array, put good elements in new array and don't delete them from input array:
<?php
$arr = [
'#EXTM3U',
'#EXTINF:177,Paul Dateh & Oren Yoel - Be More',
'Be More.mp3',
'#EXTINF:291,Christopher Toy - Just Because',
'Just Because.mp3',
'#EXTINF:238,Magnetic North - Drift Away',
'Drift Away.mp3'
];
$cleared_from_mess_array = array();
for ($i = 0; $i <= count($arr); $i++) {
if ($arr[$i]{0} != '#')
{
array_push($cleared_from_mess_array,$arr[$i]);
}
}
print_r($cleared_from_mess_array);
exit;

PHP add value in the last foreach loop

I want to add some extra values by using foreach loop.
foreach($a as $b) {
echo $b; // this will print 1 to 6
}
Now I want to edit last item with custom text
and print like this
1
2
3
4
5
6 this is last.
how can i do this? Please help I am new in PHP.
You can use end of array
<?php
$a = array(1,2,3,4,5,6);
foreach($a as $b) {
echo $b; // this will print 1 to 6
if($b == end($a))
echo "this is last.";
echo "<br>";
}
EDIT
as # alexandr comment if you have same value you can do it with key
<?php
$a = array(6,1,2,3,4,5,6);
end($a); // move the internal pointer to the end of the array
$last_key = key($a);
foreach($a as $key=>$b) {
echo $b; // this will print 1 to 6
if($key == $last_key)
echo "this is last.";
echo "<br>";
}
<?php
$a = array(1,2,3,4,5,6);
$last = count($a) - 1;
foreach($a as $k => $b) {
echo $b; // this will print 1 to 6
if($k == $last)
echo "this is last.";
echo "<br>";
}
You can declare inc variable, and use with array count
<?php
//$b is your array
$i=1;
foreach($a as $b) {
if(count($a)==$i){
echo $b; // this is last
}
$i++;
}
?>
Use count, the thats way you get the size and you can use in a condicional like if
$size=count($a);
foreach($a as $b) {
if ($b==$size)
{
echo $b. "This is the last"; // this will print 6 and text
}
else
{
echo $b; // this will print 1 to 5
}
}
You can use array_slice which is a good way to slice up an array.
You can set it to get the last item(s) with negative numbers.
$arr = array(1,2,3,4,5,6);
$last = array_slice($arr, -1, 1)[0]; // 6
$other = array_slice($arr, 0, -1); // [1,2,3,4,5]
foreach($other as $item){
echo $item;
}
echo $last . " this is the last";

PHP Loop: Every 4 Iterations Starting From the 2nd

I have an array that can have any number of items inside it, and I need to grab the values from them at a certain pattern.
It's quite hard to explain my exact problem, but here is the kind of pattern I need to grab the values:
No
Yes
No
No
No
Yes
No
No
No
Yes
No
No
I have the following foreach() loop which is similar to what I need:
$count = 1;
foreach($_POST['input_7'] as $val) {
if ($count % 2 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}
However, this will only pick up on the array items that are 'even', not in the kind of pattern that I need exactly.
Is it possible for me to amend my loop to match that what I need?
You can do this much simpler with a for loop where you set the start to 1 (the second value) and add 4 after each iteration:
for ($i = 1; $i < count($_POST['input_7']); $i += 4) {
echo $_POST['input_7'][$i] . '<br />';
}
Example:
<?php
$array = array(
'foo1', 'foo2', 'foo3', 'foo4', 'foo5',
'foo6', 'foo7', 'foo8', 'foo9', 'foo10',
'foo11', 'foo12', 'foo13', 'foo14', 'foo15'
);
for ($i = 1; $i < count($array); $i += 4) {
echo $array[$i] . '<br />';
}
?>
Output:
foo2foo6foo10foo14
DEMO
Try this:
$count = 3;
foreach($_POST['input_7'] as $val) {
if ($count % 4 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}

PHP Foreach loop take an additional step forward from within the loop

Basically I have a foreach loop in PHP and I want to:
foreach( $x as $y => $z )
// Do some stuff
// Get the next values of y,z in the loop
// Do some more stuff
It's not practical to do in a foreach.
For non-associative arrays, use for:
for ($x = 0; $x < count($y); $x++)
{
echo $y[$x]; // The current element
if (array_key_exists($x+1, $y))
echo $y[$x+1]; // The next element
if (array_key_exists($x+2, $y))
echo $y[$x+2]; // The element after next
}
For associative arrays, it's a bit more tricky. This should work:
$keys = array_keys($y); // Get all the keys of $y as an array
for ($x = 0; $x < count($keys); $x++)
{
echo $y[$keys[$x]]; // The current element
if (array_key_exists($x+1, $keys))
echo $y[$keys[$x+1]]; // The next element
if (array_key_exists($x+2, $keys))
echo $y[$keys[$x+2]]; // The element after next
}
When accessing one of the next elements, make sure though that they exist!
use the continue keyword to skip the rest of this loop and jump back to the start.
Not sure if you simply want to do just "some stuff" with the first element, only "some more stuff" with the last element, and both "some stuff" and "some more stuff" with every other element. Or if you want to do "some stuff" with the first, third, fifth elements, and "some more stuff" with the second, fouth, sixth elements, etc.
$i = 0;
foreach( $x as $y => $z )
if (($i % 2) == 0) {
// Do some stuff
} else {
// Do some more stuff
}
$i++;
}
Ok, following up on my comment on Pekka's solution, here is one that takes into account the fact that the array might be associative. It's not pretty, but it works. Suggestions on how to improve this are welcomed!
<?php
$y = array(
'1'=>'Hello ',
'3'=>'World ',
'5'=>'Break? ',
'9'=>'Yup. '
);
$keys = array_keys($y);
$count = count($y);
for ($i = 0; $i < $count; $i++) {
// Current element
$index = $keys[$i];
echo "Current: ".$y[$index]; // The current element
if (array_key_exists($i+1, $keys)) {
$index2 = $keys[$i+1];
echo "Next: ".$y[$index2]; // The next element
}
if (array_key_exists($i+2, $keys)) {
$index3 = $keys[$i+2];
echo "Nextnext: ".$y[$index3]; // The element after next
}
}
?>
try something like...
for ($i=0, $i<count($x); $i++)
{
// do stuff with $x[$i]
// do stuff with $x[$i+1], unless you're on the last element of the array
}
reset($arr);
while(list($firstindex,$firstvalue) = each($arr)){
list($secondindex,$secondvalue) = each($arr);
//do something with first & second.
}

Categories