php foreach as key, every two number as a group - php

<?php
$data=array('1','2','3','4','5','6','7','8','9','10','11');
foreach($data as $key=> $element){
if($key % 2 != 0){
echo $element.'<br />';
}
echo '<hr />';
}
?>
php foreach as key, how to make every two number as a group?
I want to output:
1,2
_____
3,4
_____
5,6
_____
7,8
_____
9,10
_____
11

Have a look at the array_chunk() function.
In your case you'd use it like this:
foreach(array_chunk($data, 2) as $values) {
echo implode(',', $values)."\n";
}
During the last iteration $values will have only one element so if you plan to access the elements directly using their index remember to use count() to check the array's element count.

Your foreach() is fine but you want to print every element, not just every even one. You also don't want the horizontal rule every time either, just every even. Thus:
<?php
$data=array('1','2','3','4','5','6','7','8','9','10','11');
foreach($data as $key=> $element){
echo $element;
if($key % 2 != 0){
echo "<br/><hr />";
}
else {
echo ",";
}
}
?>

Related

Count values with the same value inside loop

I try count elements inside loop, with the same value, as i put in my title, now i show my little script fot try to do this :
<?php
$values="1,2,3~4,5,2~7,2,9";
$expt=explode("~",$values);
foreach ($expt as $expts)
{
$expunit=explode(",",$expts);
$bb="no";
foreach($expunit as $expunits)
{
//// $expunit[1] it´s the second value in each explode
if ($expunits==="".$expunit[1]."")
{
$bb="yes";
}
if ($bb=="yes")
{
print "$expunits --- $expunit[1] ok, value it´s the same<br>";
}
else
{
print " $expunits bad, value it´s not the same<br>";
}
}
}
?>
THE SCRIPT MUST SHOW DATA IN THIS WAY :
$values="1,2,3~4,5,2~7,2,9";
**FIRST ELEMENTS WITH THE SAME SECOND ELEMENT, IN VALUES COMMON VALUE IT´S NUMBER 2, BECAUSE IT´S IN SECOND POSITION **
FIRST :
1,2,3
7,2,9
LAST THE OTHERS
4,5,2
I try verificate the second position, between delimeters, because it´s value i want verificate for count inside loop, while explode string, actually give bad values, i think it´s bad because don´t get real or right values, i don´t know if it´s possible do it or with other script or change something in this
Thank´s Regards
EDIT - this is a bit closer to what you are looking for (sorry it is not perfect as I do not have time to work on it fully):
$values="1,2,3~4,5,2~7,2,9";
$values=explode("~",$values);
foreach($values as $key => $expt) {
$expit=explode(",",$expt);
$search_value = $expit[1];
$matched=array();
foreach($values as $key2 => $expt2) {
if($key !== $key2) {
$expit2=explode(",",$expt2);
if($expit[1]==$expit2[1]) {
$matched[] = $expit[1];
}
}
}
}
array_unique($matched);
foreach($matched as $match) {
$counter = 0;
$no_matches = array();
echo "<br />Matching on digit ".$match;
foreach($values as $key3 => $expt3) {
$expit3=explode(",",$expt3);
if($match == $expit3[1]) {
echo "<br />".$expt3;
$counter++;
} else {
$no_matches[] = $expt3;
}
}
echo "<br />Total number of matches - ".$counter;
echo "<br />Not matching on digit ".$match;
foreach($no_matches as $no_match) {
echo "<br />".$no_match;
}
}
Outputs:
Matching on digit 2
1,2,3
7,2,9
Total number of matches - 2
Not matching on digit 2
4,5,2

PHP: Echo something for each 2 results

I have a simple foreach loop that outputs the information I want.
However, I want to wrap it with a div for every two results.
I tried the modulus operator with no success (the result applied for every result).
So, my code:
foreach ($result->data as $info) {
// A open div to wrap two results
echo 'something';
// An closing div to wrap the previous two results
}
This will do it!
foreach ($result->data as $i=>$info) {
if ($i % 2 == 0) echo '<div>';
echo $info;
if ($i % 2 == 1) echo '</div>';
}
if (count($result->data) % 2 == 1) echo '</div>';
exactly what you asked ;)
Most simple way: Iterate in steps of 2.
for ($cc = 0; $cc<count($result->data); $cc += 2) {
// here >> start div container for both
echo $result->data[$cc];
if (defined($result->data[$cc+1]))
echo $result->data[$cc+1];
// here >> end div container for both
}
HTML omitted for clearness.
You can also add an else branch to output a placeholder if the result contains an odd number of items.
add an index count then check that its divisible by two in the code.
IN THIS CASE the if block needs to be at the top of the foreach loop, since I started $i at 0. Please stop editing that portion :)
$i = 0;
// Create first new div before loop, here.
echo '<div>'; //first div
foreach ($result->data as $info) {
// An closing div to wrap the previous two results
if ($i % 2){
// Code here would occur after each two iterations
// IE: close div then open new one. something like this
echo '</div><div>';
}
// A open div to wrap two results
echo 'something';
$i++;
}
// close final div after loop, here.
echo '</div>';
For outputting every two results from array you can also use
<?php
$array = range( 1, 20 );
foreach( array_chunk( $array, 2 ) as $pair ) {
echo '<div>' , implode( ' ', $pair ) , '</div>';
}
// <div>1 2</div>
// <div>3 4</div>
// etc
?>
set 2 variables, string and int
save the value in string variable if the value of the int variable is not even
when the second variable is an even number
wrap in div
//just simply
<?php
foreach($result->data as $i=>$info){
if($i<5){
echo $info
}
}
?>

Foreach loop and average in PHP

I'm rather new to programming in general. I'm starting off with some exercises but I'm kind of getting stuck. I created an array and looped thru with a foreach loop to print out each individual number stored in the array, but I dont know what to do to find the average of the numbers and print it out.
<?php
$myArray = array(87,75,93,95);
foreach($myArray as $value){
echo "$value <br>";
}
?>
only as an exercise, becuse if you actully wanted to do this you would use #kittykittybangbang's answer
<?php
$myArray = array(87,75,93,95);
$sum='';//create our variable
foreach($myArray as $value){
$sum+=$value; //adds $value to $sum
//echo "$value <br>";
}
echo $sum;
?>
for the count count($myArray); makes the most senses but you could do that in the loop as well:
<?php
$myArray = array(87,75,93,95);
$sum= $count=0;// initiate interger variables
foreach($myArray as $value){
$sum+=$value; //adds $value to $sum
$count++; //add 1 on every loop
}
echo $sum;
echo $count;
//the basic math for any average:
echo $sum/$count;
?>
if you don't create $sum and $count before the loop you would get notices returned from php, as the first time it tried to add to either, there would be noting to add to
You could:
$avg = array_sum($myArray) / count($myArray);
echo $avg;
Where:
array_sum calculates the sum of all elements in the given array.
count outputs the total number of elements in the given array.

How to only show the first line of print print_r?

How do you echo only the first line of print print_r?
More info:
I have this PHP code:
preg_match_all('/MbrDtlMain.php\?([^ ]+)>/i', $string, $matches);
foreach(end($matches) as $key=> $value){
print print_r($value, 1).'<br>';
}
That results in:
12567682
12764252
12493678
14739908
(or other numbers depending on user input)
I tried:
preg_match_all('/MbrDtlMain.php\?([^ ]+)>/i', $string, $matches);
foreach(end($matches) as $key=> $value){
$id = print_r($value, 1).'<br>';
}
echo $id
But it results in 1 random number from the list. In other words, the result only shows when using print like ' print print_r($value, 1).'<br>';'. The problem is that I only want the first, inorder, result to be shown. As if:
$firstlineofnumbers = '12567682';
echo $firstlineofnumbers;
Hope this makes sense. Thanks (:
If I understood what you're trying to do, just adding a break; statement after outputting the first value should be enough:
foreach(end($matches) as $key=> $value){
print print_r($value, true).'<br>'; // print_r() expects true, not 1
break;
}
If the keys in $matches are always numeric keys, this code should be enough:
echo $matches[0];
Otherwise, try this code:
$keys = array_keys($matches);
echo $matches[array_shift($keys)];
$keys will contain all keys of $matches.
array_shift will return the first value of $keys (the first key).
So the last line will display the corresponding value.
There is no need to loop through the entire array if you only need to display the first element.
preg_match_all('/MbrDtlMain.php\?([^ ]+)>/i', $string, $matches);
$i=0;
foreach(end($matches) as $key=> $value){
$i++;
if ($i == 1) {
echo $value."<br />";
}
}
This starts with the variable $i which increases by 1 for each match. If $i == 1, then it will echo the $value.

All of array not showing?

OK, this is weird. I have an array of time blocks:
$time_block = array("09:00:00-13:00:00","10:00:00-14:00:00");
And I want to loop through them to create a start time and end time for each block:
foreach($time_block as $val)
{
for($x = 0; $x < count($time_block); $x++)
{
$time=$val[$x];
echo substr($time,0,8);
echo "<br>";
echo substr($time,-8);
}
echo "<br>";
echo "<br>";
}
The end result should be:
09:00:00
13:00:00
10:00:00
14:00:00
But I am getting:
0
09
9
1
10
0
Any thoughts?
You wrote: $time = $val[$x];
$val is not an array, it's a string, and seems like you are doing a foreach and then a for on the same array?
You can use something like:
foreach ($timeblock as $timeString) {
list($start, $end) = explode("-", $timeString);
echo "$start $end\n";
}
foreach($time_block as $v) {
print_r(explode( '-',$v ));
echo '<br><br>';
}
In your foreach loop, $val is a string. When you ask for $val[$x], your asking for the xth character of that string. Probably not what you want.
Solution:
Take out the for statement, and change
$time=$val[$x];
to
$time=$val;
Try this:
for($x = 0; $x < count($time_block); $x++){
$time = $time_block[$x];
echo substr($time,0,8);
echo "<br>";
echo substr($time,-8);
echo "<br><br>";
}
You're using 2 nested loops while you only have 1 dimension in your data set. That should make you think.
The problem with your approach is you're trying to loop through the element two times. If you use foreach($time_block as $val), in every iteration $val will be a single element of the array. For example, on the first run, it will store "09:00:00-13:00:00". So in your for loop, you were trying to loop through this $val, which is actually possible as strings can be accessed as arrays (the characters in the string being the elements).
This will produce the exact output you needed:
foreach($time_block as $val) {
$t=explode('-', $val);
echo $t[0]."<br>".$t[1]."<br><br>";
}
Here, explode() is used to separate the time values in $val based on the - character. $t will be an array, holding the two times in $val as its two elements.
In your code you are double looping, just use it like this:
$time_block = array("09:00:00-13:00:00","10:00:00-14:00:00");
foreach($time_block as $time) {
echo substr($time,0,8) . " ";
echo substr($time,-8) . "\n";
}
OUTPUT
09:00:00 13:00:00
10:00:00 14:00:00

Categories