I'm writing a string from my form and I'd like to remove the last comma from the end. I understand that I can use the rtrim(), but I don't understand how I can return a variable from my loop. I'm sure this is an easy answer, just super confused. Thanks!
if (isset($_POST['submit'])) {
foreach ( $_POST['data'] as $data )
{
echo $data['Monday'];
echo $data['Tuesday'];
echo $data['Wednesday'];
echo $data['Thursday'];
echo $data['Friday'];
echo $data['Saturday'];
echo $data['Sunday'];
echo ", ";
}
} // end if
You can check if you are on the last element and skip printing the comma if so:
end($_POST['data'); // fast forward to the end of the array
$lastKey = key($_POST['data'); // and remember what the last key is
foreach ( $_POST['data'] as $key => $data )
{
echo $data['Monday'];
echo $data['Tuesday'];
echo $data['Wednesday'];
echo $data['Thursday'];
echo $data['Friday'];
echo $data['Saturday'];
echo $data['Sunday'];
if ($key !== $lastKey) echo ", ";
}
This approach feels cleaner to me: prevention is better than treatment.
you need to have a variable
$str = null;
if (isset($_POST['submit'])) {
foreach ( $_POST['data'] as $data )
{
$str .= $data['Monday'] .
$data['Tuesday'] .
$data['Wednesday'] .
$data['Thursday'] .
$data['Friday'] .
$data['Saturday'] .
$data['Sunday'] .
", ";
}
$str = substr($str,0,-2);
}
Then you have the data in $str which you can then echo or do stuff with
You could get the last index of the $_POST['data'] and simply not echoing a , when that's reached:
end($_POST['data']);
$last_key = key($_POST['data']);
foreach ($_POST['data'] as $key => $data) {
// echoes here
if ($key != $last_key) {
echo ',';
}
}
Instead of echo'ing the data immediately, store it in a buffer...
if (isset($_POST['submit'])) {
$buffer = "";
foreach ( $_POST['data'] as $data )
{
$buffer .= $data['Monday'];
$buffer .= $data['Tuesday'];
$buffer .= $data['Wednesday'];
$buffer .= $data['Thursday'];
$buffer .= $data['Friday'];
$buffer .= $data['Saturday'];
$buffer .= $data['Sunday'];
$buffer .= ", ";
}
$buffer = rtrim($buffer, ", ");
echo $buffer;
} // end if
Or, even shorter:
if (isset($_POST['submit'])) {
implode(", ", $data);
} // end if
Assuming $data only has those Monday-Sunday keys..
Related
I have a text file generated from our banking software which looks like this:
This is my code to print the text file contents line by line:
<?php
$myFile = "20151231.txt";
$lines = file($myFile);
foreach ($lines as $line_num) {
echo htmlspecialchars($line_num)."<br>";
}
It prints like this:
I just want each line that starts with:
====>
I want everything else deleted.
I tried a lot but failed to print lines with the columns separated as it looks in the text file image.
This is how I want each line to print:
====>0518 Intt on Consumer Loan 401010707 108,149.00
Your assistance regarding this will be highly appreciated.
You can print it as a table:
<?php
$myFile = "20151231.txt";
$lines = file($myFile);
echo '<table>';
foreach ($lines as $line_num) {
if (strpos($line_num, '====>') !== false) {
$str = trim(htmlspecialchars($line_num));
echo '<tr>';
echo '<td>' . getColumnText("/====>\d+/", $str) .'</td>';
echo '<td>' . getColumnText("/\s([a-zA-Z\s]+)/", $str) .'</td>';
$secondCol = getColumnText("/\s([0-9]+)/", $str);
echo '<td>' . $secondCol .'</td>';
$thirdCol = end(explode(" ", $str));
if (trim($secondCol) === $thirdCol) {
echo '<td style="text-align:right">' . str_repeat(" ", 10) .'</td>';
} else {
echo '<td style="text-align:right">' . str_repeat(" ", 10) . $thirdCol .'</td>';
}
echo '</tr>';
}
}
echo '</table>';
function getColumnText($pattern, $str) {
preg_match($pattern, $str, $matches);
return trim(current($matches));
}
yes you can do that with strpos or regularexpression and i am just writing code using strpos
<?php $myFile = "text.txt";
$lines = file($myFile);
echo '<table cellspacing="20">';
$linenum = 1;
foreach ($lines as $line_num) {
echo '<tr>';
// check whether line conatain ====>, if you want to check starting of line then just put 0 instead of false in following condition
if(strpos($line_num,'====>')!==false)
{
$texts= substr($line_num, strpos($line_num,'====>')+5);
$textarr = explode(" ", $texts);
echo '<td>'.$linenum.'</td>';
foreach($textarr as $arr)
{
echo '<td>'.$arr.'</td>';
}
$linenum++;
//print_r($textarr);
//echo htmlspecialchars($line_num)."<br>";
}
}
echo '<table>';
I have a PHP while LOOP, and I want to remove last comma , from echo '],'; if it is last loop
while($ltr = mysql_fetch_array($lt)){
echo '[';
echo $ltr['days']. ' ,'. $ltr['name'];
echo '],';
}
Create an array with the elements as you go along so that they look like array = ([ELEMENT INFO], [ELEMENT INFO], [ELEMENT INFO]) and then implode the array with a comma.
$str = '';
while($ltr = mysql_fetch_array($lt)){
$str .= '[';
$str .= $ltr['days']. ' ,'. $ltr['name'];
$str .= '],';
}
echo rtrim($str, ",");
this will remove the last , from string
I think the systemic solution is following:
$separator = '';
while($ltr = mysql_fetch_array($lt)){
echo $separator;
echo '[';
echo $ltr['days']. ' ,'. $ltr['name'];
echo ']';
if (!$separator) $separator = ', ';
}
No call for count(), no additional iteration of implode(), no additional string operations, ready for any (unpredictable) number of results.
$result = mysql_fetch_array($lt);
for ($i=0;$i<=(count($result)-1);$i++) {
$ltr = $result[$i];
echo '[';
echo $ltr['days']. ' ,'. $ltr['name'];
echo ']';
if(!count($result)-1 == $i){
echo ',';
}
}
Check how many entries you have, make a "Counter" and a condition to only put the comma when its not the last loop.
$arr = array();
while($ltr = mysql_fetch_array($lt)){
$arr[] = '[' . $ltr['days'] . ' ,' . $ltr['name'] . ']';
}
echo implode(',', $arr);
$res_array = array();
while($ltr = mysql_fetch_array($lt)){
$res_array[] = '['.$ltr['days']. ' ,'. $ltr['name'].']';
}
$str = implode(",",$res_array);
echo $str;
Save the response as a var instead of echoing it and then remove the final character at the end using substr.
$response = "";
while($ltr = mysql_fetch_array($lt)){
$response .= '[';
$response .= $ltr['days']. ' ,'. $ltr['name'];
$response .= '],';
}
echo substr($response, 0, -1);
//this one works
$result = mysql_fetch_array($lt);
for ($i=0;$i<=(count($result)-1);$i++) {
$ltr = $result[$i];
echo '[';
echo $ltr['days']. ' ,'. $ltr['name'];
echo ']';
if(count($result)-1 != $i){
echo ',';
}
}
This one only covers the first record in the array -- $form[items][0][description]. How could I iterate this to be able to echo succeeding ones i.e
$form[items][1][description];
$form[items][2][description];
$form[items][3][description];
and so on and so forth?
$array = $form[items][0][description];
function get_line($array, $line) {
preg_match('/' . preg_quote($line) . ': ([^\n]+)/', $array['#value'], $match);
return $match[1];
}
$anchortext = get_line($array, 'Anchor Text');
$url = get_line($array, 'URL');
echo '' . $anchortext . '';
?>
This should do the trick
foreach ($form['items'] as $item) {
echo $item['description'] . "<br>";
}
I could help you more if I saw the body of your get_line function, but here's the gist of it
foreach ($form['items'] as $item) {
$anchor_text = get_line($item['description'], 'Anchor Text');
$url = get_line($item['description'], 'URL');
echo "{$anchor_text}";
}
You can use a for loop to iterate over this array.
for($i=0; $i< count($form['items']); $i++)
{
$anchortext = get_line($form['items'][$i]['description'], 'Anchor Text');
$url = get_line($form['items'][$i]['description'], 'URL');
echo '' . $anchortext . '';
}
I'm using a foreach loop to echo out some values from my database, I need to strip the last comma from the last loop if that makes sense.
My loop is just simple, as below
foreach($results as $result){
echo $result->name.',';
}
Which echos out
result,result,result,result,
I just need to kill that pesky last comma.
Better:
$resultstr = array();
foreach ($results as $result) {
$resultstr[] = $result->name;
}
echo implode(",",$resultstr);
1. Concat to string but add | before
$s = '';
foreach ($results as $result) {
if ($s) $s .= '|';
$s .= $result->name;
}
echo $s;
2. Echo | only if not last item
$s = '';
$n = count($results);
foreach ($results as $i => $result) {
$s .= $result->name;
if (($i+1) != $n) $s .= '|';
}
echo $s;
3. Load to array and then implode
$s = array();
foreach ($results as $result) {
$s[] = $result->name;
}
echo implode('|', $s);
4. Concat to string then cut last | (or rtrim it)
$s = '';
foreach ($results as $result) {
$s .= $result->name . '|';
}
echo substr($s, 0, -1); # or # echo rtrim($s, '|');
5. Concat string using array_map()
echo implode('|', array_map(function($result) { return $result->name; }, $results));
$result_names = '';
foreach($results as $result){
$result_names .= $result->name.',';
}
echo rtrim($result_names, ',');
I've been having the same issue with this similar problem recently. I fixed it by using an increment variable $i, initializing it to 0, then having it increment inside the foreach loop. Within that loop place an if, else, with the echo statement including a comma if the $i counter is less than the sizeof() operator of your array/variable.
I don't know if this would fix your issue per se, but it helped me with mine. I realize this question is years-old, but hopefully this will help someone else. I'm fairly new to PHP so I didn't quite understand a lot of the Answers that were given before me, though they were quite insightful, particularly the implode one.
$i=0;
foreach ($results as $result) {
$i++;
if(sizeof($results) > $i) {
echo $result . ", ";
} else {
echo $result;
}
}
In modern PHP, array_column() will allow you to isolate a column of data within an array of objects.
Code: (Demo)
$results = [
(object)['name' => 'A'],
(object)['name' => 'B'],
(object)['name' => 'C']
];
echo implode(',', array_column($results, 'name'));
Output:
A,B,C
That said, since you are iterating a result set, then you may be better served by calling a CONCAT() function in your sql, so that the values are already joined in the single value result set.
If you are processing a collection in Laravel, you can pluck() and implode():
$collection->pluck('name')->implode(',')
$arraySize = count($results);
for($i=0; $i<$arraySize; $i++)
{
$comma = ($i<$arraySize) ? ", " : "";
echo $results[$i]->name.$comma;
}
Not as pretty, but also works:
$first=true;
foreach($results as $result){
if(!$first) { echo ', '; }
$first=false;
echo $result->name;
}
Another smart way is:
foreach($results as $result){
echo ($passed ? ',' : '') . $result->name;
$passed = true;
}
In this case at first loop $passed is NULL and , doesn't print.
I know this is an old thread, but this came up recently and I thought I'd share my alternate, cleaner way of dealing with it, using next().
$array = array("A thing", "A whatsit", "eighty flange oscillators");
foreach( $array as $value ){
echo $value;
$nxt = next($array);
if($nxt) echo ", "; // commas between each item in the list
else echo ". And that's it."; // no comma after the last item.
}
// outputs:
// A thing, A whatsit, eighty flange oscillators. And that's it.
play with it here
I have to do this alot because I'm always trying to feed numbers in to jplot, I find its easier to put the comma in the front of the loop like so:
foreach($arrayitem as $k){ $string = $string.",".$k;
}
and then chop off the first character (the comma) using substr, it helps if you know a guestimate of long your string will be, I'm not sure what the limit on substr max character is.
echo substr($a,1,10000000);
hope this helps.
$a[0] = 'John Doe';
$a[1] = 'Jason statham';
$a[2] = 'Thomas Anderson';
$size = count($a);
foreach($a as $key=>$name){
$result .= $name;
if($size > $key+1) $result .=', ';
}
echo $result;
<?php
$return = array(any array)
$len = count($return);
$str = '';
$i = 1;
foreach($return as $key=>$value)
{
$str .= '<a href='.$value['cat_url'].'>'.$value['cat_title'].'</a>';
if($len > $i)
{
$str .= ',';
$i = $i+1;
}
}
echo $str;
?>
<?php
$i = 1;
$count = count( $results );
foreach( $results as $result ) {
echo $result->name;
if ( $i < $count ) echo ", ";
++$i;
}
?>
This is what I normally do, add a comma before the item rather than after, while ignoring the first loop.
$i = 0;
$string = '';
foreach($array as $item){
$string .= ($i++ ? ',' : '').$item;
}
First get all the output by using output buffering. Then, trim the comma and display it. So, do it like this:
ob_start();
foreach($results as $result)
{
echo $result->name.',';
}
$output = ob_get_clean();
echo rtrim($output, ',');
The output buffering method helps if the inside loop is very big (and OP is posting here just for brevity), then using OB is easier without changing the internals of the loop.
How do I print out all the parameters and their value from a URL without using e.g. print $_GET['paramater-goes-here']; multiple times?
I use
print_r($_GET);
foreach($_GET as $key => $value){
echo $key . " : " . $value . "<br />\r\n";
}
The parameters are in the URL, so are available in $_GET ; and you can loop over that array using foreach :
foreach ($_GET as $name => $value) {
echo $name . ' : ' . $value . '<br />';
}
Its easy to get all request parameters from url.
<?php
print_r($_REQUEST);
?>
This will return an array format.
You can also use parse_url() and parse_str():
$url = 'http://www.example.com/index.php?a=1&b=2&c=3&d=some%20string';
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query);
parse_str($query, $arr);
echo $query; // a=1&b=2&c=3&d=some%20string
echo $a; // 1
echo $b; // 2
echo $c; // 3
echo $d; // some string
foreach ($arr as $key => $val) {
echo $key . ' => ' . $val . ', '; // a => 1, b => 2, c => 3, d => 4
}
Try this.....
function get_all_get()
{
$output = "?";
$firstRun = true;
foreach($_GET as $key=>$val) {
if(!$firstRun) {
$output .= "&";
} else {
$firstRun = false;
}
$output .= $key."=".$val;
}
return $output;
}
i use:
ob_start();
var_dump($_GET);
$s=ob_get_clean();
i use:
$get = $_REQUEST;
$query_string = '?';
foreach ($get as $key => $value) {
$query_string .= $key . '=' . $value . '&';
}
$query_string;