How to get only one result from foreach(PHP) - php

The code loop an array and display all views for a user. Now things changed and I just need to display one result from a foreach loop. How do I do that?
<table class="report_edits_table">
<thead>
<tr class="dates_row">
<?php foreach($report['edits'] as $report_edit) : ?>
<td colspan="2" report_edit_id="<?php echo $report_edit['id'] ?>"><div class="date_container">
<?php if($sf_user->hasCredential(Attribute::COACHING_EDIT_ACCESS)) : ?>
<span class="ui-icon ui-icon-trash">Remove</span>
<?php endif?>
<?php echo "View " . link_to($report_edit['created'], sprintf('coaching/viewReportEdit?reportedit=%s', $report_edit['id']), array('title' => 'View This Contact')) ?> </div></td>
<?php endforeach ?>
</tr>
</thead>
<tbody>
<?php foreach($report['edits_titles'] as $index => $title) : ?>
<tr class="coach_row">
<?php for ($i=max(0, count($report['edits'])-2); $i<count($report['edits']); $i++) : $report_edit = $report['edits'][$i] ?>
<td class="name_column"><?php echo $title ?></td>
<td class="value_column"><?php echo $report_edit[$index] ?></td>
<?php endfor ?>
</tr>
<?php endforeach ?>
</tbody>

Use the break command for simple conversion:
<?php for ... ?>
... stuff here ...
<?php break; ?>
<?php endfor ... ?>
A better solution would be to remove the foreach completely.

It sounds like you want to grab the first element from an array without having to loop through the rest of them.
PHP provides a set of functions for situations like this.
To get the first element in an array, start off using the reset() function to position the array pointer to the start of the array, then use the current() function to read the element that the pointer is looking at.
So your code would look like this:
<?php
reset($report['edits']);
$report_edit = current($report['edits']);
?>
Now you can work with $report_edits without having to use a foreach() loop.
(note that the array pointer does actually start by default at the first record, so you could skip the reset() call, but it's best practice not to do that because it might have been changed elsewhere in your code without you realising it)
If you want to move on to the next record after that, you can use the next() function. As you can see, if you wanted to, it would theoretically be possible to use these functions to write an alternative type of foreach() loop. There wouldn't be any point in using them them that way, but it's possible. But they do allow more fine-grained control over the array, which is handy for situations like yours.
Hope that helps.

Plenty of ways
Access the index of the array element in question directly
Update whatever logic fetches/generates the array to only return the element of interest
Use a for loop that terminates after a single loop
array_filter your array to get the element of interest
Break at the end of your foreach loop so it terminates after the first iteration
Conditionally check your index in the foreach loop and only output markup if the index matches the element of interest
And so on
I'd recommend just getting the array element of interest (number 2 on the list) as it means less data bouncing around your code (and probably between your PHP box and the database if you're populating the array from an SQL server)

Simplest method?
Place a break as the last line of your foreach. It'll execute once, then quit. (As long as which element you stop on is of no importance).
Secondary method: use array_pop or array_shift on your $report['edits'] or $report['edits_titles'] to get on element, lose the for loop, and reference the element you just retrieved.
For example:
//
// current
//
foreach ($report['edits'] as $report_edit) :
/* markup */
endforeach;
//
// modified version
//
$report_edit = array_shift($report['edits']);
/* markup */

Use <?php break ?> before <?php endforeach ?>

example ::
<?php
foreach ($this->oFuelData AS $aFuelData ) {
echo $aFuelData['vehicle'];
break;
}
?>

You can also use it for reference
foreach($array as $element) {
if ($element === reset($array))
echo $element;
if ($element === end($array))
echo $element;
}

Related

Foreach table output rows near each other

I have json html table in php, now i can't get it work that the output in the table will be near each other.
I am already few days busy with this, hope some one can help me.
<?php foreach($data2 as $row): ?>
<tr>
<td><?=$row['model'];?></td>
<td><?=$row['model2'];?></td>
</tr>
<?php endforeach;?>
My json output:
It looks like the JSON is not formatted for what you are trying to do. Every object has either modal or modal2, so the one that is not filled is undefined.
You should get the length of the longest list and use a normal for loop.
<?php ($index = 0; $index <= $lengthOfLongestList; $index++): ?>
<tr>
<td><?=$data2[index]['model'];?></td>
<td><?=$data2[index]['model2'];?></td>
</tr>
<?php endforeach;?>

Multiple foreach loops

I'd like to have 2 foreach loops for 2 arrays like that, I know it's wrong:
$properties has 6 items and $set_properties has 11 items
<?php if(!empty($properties)) : foreach ($properties as $prop) : ?>
<?php if(!empty($set_properties)) : foreach ($set_properties as $set_prop) : ?>
<?php endforeach; endif; ?>
<?php endforeach; endif; ?>
What would be the right way, because right now I'm getting too many loops if I want to echo something out ($prop->ID).
My goal is to make dropdown selectors($properties) and have $set_properties as options.
Try the following snippet, which I commented to hopefully help you understand.
//check if properties is empty, if not, loop through them.
if(!empty($properties)):
foreach ($properties as $prop):
//check if $set_properties is empty, if not create select element
if(!empty($set_properties)):
//loop through properties, generate select element for current index
//obviously you can do proper select element naming and everything I just don't know your markup
//notice I do this after checking if the options fields are empty, so that way it only appears if there are options associated with it.
echo $prop->ID.": <select>";
//loop through set_properties, generate options
foreach ($set_properties as $set_prop):
echo "<option value='{$set_prop->ID}'>{$set_prop->Name}</option>";
endforeach;
//end select element, so next iteration will make a new one.
//again, inside the check for $set_properties because the select element will only exist if options exist
echo "</select>";
endif;
endforeach;
endif;
In your original code you switch in and out of PHP very often, and that is really not necessary, it makes the code look messy and it's harder to format. Just write it all in PHP as there isn't much HTML that goes into it. You should only switch in/out of PHP if you are only trying to insert a variable into an element, or if there is a lot of HTML.

Showing the first element in an foreach array in HTML

I have an array $category['transactions']. It stores data as follow:
ID Name Phone
1 Test Test2
2 Test3 Test4
It's because I use the same array for different purpose, at one of the scenario is to show only the first record in this array. I don't what to change the coding in php nor creating a different parameter. What can I improve based on the following coding in html to get the first record only in this array?
<?php foreach($category['transactions'] as $transaction) { ?>
<div><?php echo $transaction['id']; ?></div>
<div><?php echo $transaction['name']; ?></div>
<?php } ?>
replace your code with.
<?php $firstRow=reset($category['transactions']);
echo '<div>',$firstRow['id'],'</div>';
echo '<div>',$firstRow['name'],'</div>';
?>
You don't need to iterate through the array to get the first element.
You don't even need the foreach to get the first element. Just use array_values():
$first = array_values($category['transactions')[0]
try this..
<?php
foreach($category['transactions'] as $transaction)
{
echo $transaction['id'];
break;
}
?>
and no need to use multiple php tags...

json_encode returns only one object

I have this piece of code in one single file
//declaring something
$array=array();
$arraylst=/*retrieve from database query and sure this contains the correct result*/
<?php
if(!empty($array)):
?>
<div id="something">
<?php
$n=0;
foreach($arraylst as $key=>$val):
$array="span".$n;
//create a span and print out $val's property1
$n++;
endforeach;
$n=0;
foreach($array as $key=>$val):
//create a span and print out $val's property2
$n++;
endforeach;
</div>
<?php
endif;
?>
<script language="javascript">
var arr=[<?php echo json_encode($array); ?>]
//do something else
</script>
The output to the screen I see is only one "span"; that is if my arraylst size is 3, I can only see the first span because my database query is sorted ascendingly. The rest is not seen at all.
$array="span".$n; overwrites the array with a string.
Use array_push( $array, "span$n" ); to add an item to the array.
(Then you'll want to remove the [ and ] from around the json_encode as you'll have an array in $array).
You always set the value "span" to $array.
$array="span".$n;
You do not add it to the array you set the array to that value.
Use:
$array[] ="span".$n;

sql, php, html table question

I want to grab data from a mysql database by using php. The data looks something like this:
apple 3
orange 2
banana 4
I want to take the data and put it in a html table and use css to make it look pretty, but I dont want to deal with it inside <?php ?>
After I grab the
$result = mysql_query("SELECT * FROM Table");
can I reference the result variable outside the <? php ?> tags?
No. PHP can only be done in <?php ... ?> or <?= ... ?>. Use a template engine such as Smarty if you want substitution in this manner.
in short, no you cant, it is a php variable (technically a resource in this case) so you have to parse it through the php engine, which requires the php tags
echo '<table>';
while ($row = mysql_fetch_assoc($result)) {
echo '<tr><td>'.$row['fruit'].'</td><td>'.$row['id'].'</td></tr>';
}
echo '</table>';
Short answer is no. HTML cannot deal with dynamic content.
If you want to cut down the amount of echo statements within your code you can store the html within a given variable and then make reference to it.
I find it better to do the following:
<table>
<?php foreach($result as $row): ?>
<tr>
<td><?php echo $row['fruit']?></td>
<td><?php echo $row['id']?></td>
</tr>
<?php endforeach; ?>
</table>
This provides clarity and minimizes concatenation.

Categories