how to break foreach loop - array index - php

My array which is dynamic, formed as
$exam = explode(',',$row['exam']);
For example result is:
$exam = array("First-Term","Second-Term", "Third-Term");
We can get index and value as this
foreach (array_values($exam) as $i => $value) {
echo "$i: $valuen";
echo "//And its mark";
}
But, how can I break loop to each index. I have to fetch as follow
First-Term
//And its mark
Second-Term
// And its mark
Third-Term
// And its mark
But while using foreach loop, I am getting
First-Term
Second-Term
Third-Term
//And its mark
//And its mark
//And its mark
How to break loop to each index, after that we use same code in every index. I'm simply try to assign each marks to each term
$exam[0]{
//here is $value
//rest of the code, same code to every index
}
$exam[1]{
//here is $value
//rest of the code, same code to every index
}
$exam[2]{
//here is $value
//rest of the code, same code to every index
}
$exam[...]{
//
}

You should make two arrays for team and marks and then parse these two arrays in the same foreach loop like this
$team = array('a', 'b', 'c', 'd' );
$marks = array('1', '2', '3', '4' );
foreach(array_combine($team, $marks) as $t => $m) {
echo $t . "<br>" .$m . "<br><br>"; //$t for team and m for marks
echo "<br/>";
}
In this way you can parse your different data in a paralell way

From the looks of what you are doing, you are using two foreach loops with different output...
This one:
$exam = array("First-Term","Second-Term", "Third-Term");
foreach (array_values($exam) as $i => $value) {
echo "{$value}<br>";
echo "// And its mark<br><br>";
}
Will output this:
First-Term
//And its mark
Second-Term
// And its mark
Third-Term
// And its mark
While this loop:
$exam = array("First-Term","Second-Term", "Third-Term");
foreach (array_values($exam) as $i => $value) {
echo "{$value}<br>";
}
foreach (array_values($exam) as $i => $value) {
echo "// And its mark<br>";
}
Will output this:
First-Term
Second-Term
Third-Term
// And its mark
// And its mark
// And its mark
Will update this answer once I have more details.
Code tested: https://3v4l.org/RDvYN

I would build an array with everything in place and then start to display it:
$exam = array("First-Term","Second-Term", "Third-Term");
$marks = array(1, 2, 3);
$result = array();
foreach (array_values($exam) as $idx => $value) {
$result[] = array(
"exam" => $value,
"mark" => $marks[$idx]
);
}
foreach ($result as $value) {
echo $value['exam'] . "\n";
echo $value['mark'] . "\n\n";
}

Related

How can I get only the first two elements of an array by using a foreach loop in PHP?

I have an array like this:
$aMyArray = array(
"bmw"=>"user1",
"audi"=>"user2",
"mercedes"=>"user3"
);
And I only want to show the first two elements bmw=>user1 and audi=>user2.
But I want it by using a foreach loop.
If you want the first 2 by name:
Using in_array (documentation) is what you looking for:
$aMyArray = array("bmw"=>"user1", "audi"=>"user2", "mercedes"=>"user3");
$valuesToPrint = array("bmw", "audi");
foreach($aMyArray as $key => $val) {
if (in_array($key, $valuesToPrint))
echo "Found: $key => $val" . PHP_EOL;
}
If you want the first 2 by index use:
init index at 0 and increment in each iteration as:
$aMyArray = array("bmw"=>"user1", "audi"=>"user2", "mercedes"=>"user3");
$i = 0;
foreach($aMyArray as $key => $val) {
echo "Found: $key => $val" . PHP_EOL;
if (++$i > 1)
break;
}
$counter = 1;
$max = 2;
foreach ($aMyArray as $key => $value) {
echo $key, "=>", $value;
$counter++;
if ($counter === $max) {
break;
}
}
It is important to break execution to avoid arrays of any size looping until the end for no reason.
<?php
$aMyArray = array(
"bmw"=>"user1",
"audi"=>"user2",
"mercedes"=>"user3"
);
reset($aMyArray);
echo key($aMyArray).' = '.current($aMyArray)."\n";
next($aMyArray);
echo key($aMyArray).' = '.current($aMyArray)."\n";
Easiest way:
$aMyArray=array("bmw"=>"user1","audi"=>"user2","mercedes"=>"user3");
$i=0;
foreach ($aMyArray as $key => $value) {
if($i<2)
{
echo $key . 'and' . $value;
}
$i++;
}
I know you're asking how to do it in a foreach, but another option is using array travelling functions current and next.
$aMyArray = array(
"bmw"=>"user1",
"audi"=>"user2",
"mercedes"=>"user3"
);
$keys = array_keys($aMyArray);
//current($array) will return the value of the current record in the array. At this point that will be the first record
$first = sprintf('%s - %s', current($keys), current($aMyArray)); //bmw - user1
//move the pointer to the next record in both $keys and $aMyArray
next($aMyArray);
next($keys);
//current($array) will now return the contents of the second element.
$second = sprintf('%s - %s', current($keys), current($aMyArray)); //audi - user2
You are looking for something like this
$aMyArray = array(
"bmw"=>"user1",
"audi"=>"user2",
"mercedes"=>"user3"
);
foreach($aMyArray as $k=>$v){
echo $v;
if($k=='audi'){
break;
}
}

Getting formatted result with nested arrays in PHP

I am trying to generate sql statement dynamically with loops but i am not getting any idea on how to do it with html name array.
assuming $name and $message are post arrays ... and assuming length of both will be equal,
following is a method i tried;
<?php
$name = array('name1','name2' );
$mess= array('message1','message2' );
$values = array($name,$mess);
foreach ($values as $key){
foreach ($key as $value){
echo $value.",";
}
}
?>
output is =
name1,name2,message1,message2,
but i want output as =
(name1,message1),(name2,message2),
Edit : I have acess to $values only and I will not be able to determine how many values are going to join in $values ..
like it can be
$values=array($name,$message,$phone);
and the result i want will be
(name1,message1,phone1),(name2,message2,phone2)
My solutions is
Step 1: Loop your $values this will gonna loop every index of your array like $name
foreach($name as $index => $value) {
// do something
}
Step 2: Inside your loop values start with ( which mean wrap your detail in (
echo "(";
Step 3: loop parent array
foreach($values as $key => $arr) {
// do something
}
Step 4: Inside the loop of your parent array display each data according to your index
echo $values[$key][$index];
$key represents the index of your parent array while $index represents the index of your child array like $name
this loop will create data like
(name1,message1,phone1)
and I just add this
if ($key < sizeof(array_keys($values))-1) {
echo ",";
}
to avoid adding , after the last loop
This code will dynamically display array you put inside $values
So your code would be like this
$name = array('name1','name2','name3','name4' );
$mess= array('message1','message2','message3','message4' );
$phone= array('phone1','phone2','phone3','phone4' );
$married= array('yes','no','yes','yes' );
$values = array($name,$mess,$phone);
foreach($name as $index => $value) {
echo "(";
foreach($values as $key => $arr) {
echo $values[$key][$index];
if ($key < sizeof(array_keys($values))-1) {
echo ",";
}
}
echo "),";
}
Demo
or this
$name = array('name1','name2','name3','name4' );
$mess= array('message1','message2','message3','message4' );
$phone= array('phone1','phone2','phone3','phone4' );
$values = array($name,$mess,$phone);
foreach($name as $index => $value) {
$join = array();
foreach($values as $key => $arr) {
$join[] = $values[$key][$index];
}
echo "(".implode(",",$join)."),";
}
Demo
$name = array('name1','name2' );
$mess = array('message1','message2' );
foreach ($names as $k => $v){
echo "(".$v.",".$mess[$k]."),";
}
Try this, you not need two foreach loop, only use foreach loop and pass key to other array and get value
$name = array('name1','name2' );
$mess= array('message1','message2' );
$values = array($name,$mess);
foreach ($name as $keys => $vals)
{
echo "(".$vals.",".$mess[$keys]."),";
}
DEMO
You can use arrap_map() function in order to join two array. Here is reference http://php.net/manual/en/function.array-map.php
<?php
$name = array('name1','name2' );
$mess= array('message1','message2' );
$value = array_map(null, $name, $mess);
print_r($value);
?>

How to get position of a value in a php array

<?php
$arr1 = preg_split("/[;]+/", $data);
foreach ($arr1 as $arr1 => $value) {
echo '<td>';
echo $value;
echo '</td>';
if (key($value)==6)
{
echo '</tr>';
echo '<tr>';
}
}
?>
This is code I am using but the key function is not returning anything.
I want to get return the position of $value and want to excecute some code if it is divisible by 6.
How can I get the position of $value in $arr1?
You must use a different variable than $arr1 to store the key.
Use this instead, where $key will be the key:
<?php
$arr1 = preg_split("/[;]+/", $data);
foreach ($arr1 as $key => $value) {
echo '<td>';
echo $value;
echo '</td>';
if ($key==6)
{
echo '</tr>';
echo '<tr>';
}
}
?>
You can following example to get position of particular $value in array.
<?php
$value = 'green';
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key_of_particular_value = array_search($value, array);
//After perform above operation $key_of_particular_value = 2
//Below statement will check whether key is divided by 6 or not
if(($key_of_particular_value % 6) == 0)
{
//perform your operation
}
?>
To know more please refer following link-
http://php.net/manual/en/function.array-search.php
You have used same variable $arr1 for key and original array, try using another variable to get key(index)
foreach ($arr1 as $key => $value) {

Echo selected values from an associate array

i dont want to echo the last two values in an associative array, couldn's figure it out, please help.
foreach($_POST as $key => $value){
echo $value;
}
This echoes all the values, i want to echo all but the last 2.
Just count the loops and dont print the value in the last two loops.
$i = 0;
foreach($_POST as $key => $value) {
$i++;
if($i != count($_POST) && $i != count($_POST)-1) {
echo $value;
}
}
It should work to slice the array before you loop it.
<?php
$newArray = array_slice( $_POST, 0, count($_POST)-2);
foreach( $newArray AS $key => $value ) {
echo $value;
}
If you want to keep your $key value, then set the 4th parameter to true to "preserve keys":
http://php.net/manual/en/function.array-slice.php
Maybe this is just an exercise, but I do want to note, in addition, that relying on the exact order of your POST'd elements sounds like a bad design idea that could lead to future problems.
I'd rather do this:
$a = array('a' => 'q','s' => 'w','d' => 'e','f' => 'r');
$arr_count = count($a) - 2;
$i = 1;
foreach($a as $k => $val){
echo $k.' - '.$val.PHP_EOL;
if ($i == $arr_count) break;
$i++;
}
Another alternative solution:
<?php
$tot=count($_POST)-2;
while ($tot--) {
// you can also retrieve the key using key($_POST);
echo current($_POST);
next($_POST);
}

How to echo out the values of this array?

How to echo out the values individually of this array?
Array ( [0] => 20120514 [1] => My Event 3 )
so
echo $value[0]; etc
I have this so far:
foreach (json_decode($json_data_string, true) as $item) {
$eventDate = trim($item['date']);
// positive limit
$myarray = (explode(',', $eventDate, 2));
foreach ($myarray as $value) {
echo $value;
}
This echo's out the whole string no as an array. and if i do this?
echo $value[0};
Then I only get 2 characters of it??
The print_r :
Array ( [0] => 20120430 [1] => My Event 1 )
foreach ($array as $key => $val) {
echo $val;
}
Here is a simple routine for an array of primitive elements:
for ($i = 0; $i < count($mySimpleArray); $i++)
{
echo $mySimpleArray[$i] . "\n";
}
you need the set key and value in foreach loop for that:
foreach($item AS $key -> $value) {
echo $value;
}
this should do the trick :)
The problem here is in your explode statement
//$item['date'] presumably = 20120514. Do a print of this
$eventDate = trim($item['date']);
//This explodes on , but there is no , in $eventDate
//You also have a limit of 2 set in the below explode statement
$myarray = (explode(',', $eventDate, 2));
//$myarray is currently = to '20'
foreach ($myarray as $value) {
//Now you are iterating through a string
echo $value;
}
Try changing your initial $item['date'] to be 2012,04,30 if that's what you're trying to do. Otherwise I'm not entirely sure what you're trying to print.
var_dump($value)
it solved my problem, hope yours too.

Categories