PHP - remove comma from the last loop - php

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 ',';
}
}

Related

php wont let me echo JSON string

Throught an AJAX call I want to pick some data from DB and send back to client.
$result is return value of SELECT QUERY
Case1:This works fine
$str = "[";
while($row = mysqli_fetch_assoc($result)) {
$str = $str ."{".
'"Name":'. '"'. $row["Name"] . '"'
. "},";
}
}
$str = $str . "]";
echo str;
CASE2:This works fine too:
$str = "[";
while($row = mysqli_fetch_assoc($result)) {
$str = $str ."{".
'"ID":'. '"'. $row["ID"] //SEE HERE
. "},";
}
} else {
echo "0 results";
}
$str = $str . "]";
echo $str;
CASE3: BUT FOLLOWING GIVES error with 500()
$str = "[";
while($row = mysqli_fetch_assoc($result)) {
$str = $str ."{".
'"ID":'. '"'. $row["ID"] . '",' //SEE HERE
'"Name":'. '"'. $row["Name"] . '"'
. "},";
}
} else {
echo "0 results";
}
$str = $str . "]";
echo $str;
I want to send echo str after making it in JSON format and parse it at client side using `JSON.parse(). Case1 and 2 work fine when I have only one key-value pair. But as soon as I put 2 key-value pairs I get error:
POST https://******************.php 500 ()
You really need to use the appropriate functions.
Get into good programming habits.
$rtn = []; //create array
while($row = mysqli_fetch_assoc($result)){
//push result into array
$rtn[] = ['ID'=> $row["ID"], 'Name'=> $row['Name']];
}
if($rtn)//if array has entries
echo json_encode($rtn);//encodes result to json
else
echo "0 results";
It return 500, because you have error in your script. You can add below code and check where is the mistake.
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
Probably in your code is missing dot. Check this:
$str = $str . "{" .
'"ID":' . '"' . $row["ID"] . '",' .
'"Name":' . '"' . $row["Name"] . '"'
. "},";

Removing last comma in the foreach query in php mysql

Im using a foreach loop to echo out some values from my database and seperating each of them by commas but last comma how we can remove
echo $string='"paymentmethods":';
echo $string='"Bank":[';
$sql2 = "SELECT * FROM paymentmethods where cid=587 ";
$query = $this->db->query($sql2);
foreach ($query->result() as $row){
echo '{';
echo $string = 'accname:'.$row->acc.',' ;
echo $string = 'country:'.$row->IBAN.',' ;
echo $string = 'Iban:'.$row->Bankname.',' ;
echo $string = 'Bankname:'.$row->Bankname.',' ;
echo $string = '},';
}
echo $string = '],';
"paymentmethods":"Bank":[{accname:0034430430012,country:AE690240002520511717801,Iban:ARABIC BANK NAME,Bankname:ARABIC BANK NAME,},{accname:0506796049,country:DE690240002520511717801,Iban:ARABIC BANK NAME,Bankname:ARABIC BANK NAME,},]
Here see the comma is repeating after the name ends. and also after the end of brackets
The comma is there because you have written it in your code. Change the lines to this :
// same as above
echo $string = 'Bankname:'.$row->Bankname. ;
echo $string = '}';
}
echo $string = ']';
a common way to do this is to do this way :
$sep = '';
$result = '';
foreach($myarray as $value) {
$result .= $sep.$value;
$sep = ',';
}
this way, you don't have a beginning or ending comma.
But as comments say, you are doing a "json_encode" by yourself... you should use json_encode / decode instead.

PHP remove the last character from my loop

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..

PHP For Each Loop? There has to be a better way

<?php
header("Content-type: text/plain");
$GLOBALS["db_name"] = "fggff_highscores";
$GLOBALS["table_name"] = "testing";
$GLOBALS["view_user"] = "fgfggg_players";
$GLOBALS["view_pass"] = "removed";
$username = strip_tags($_GET["player"]);
$fileContents = #file_get_contents("http://hiscore.runescape.com/index_lite.ws?player=" . $username);
echo $fileContents;
if ($fileContents == FALSE) {
die("PLAYER NOT FOUND");
}
//$content = array();
$data = explode("\n", $fileContents);
/*
foreach ($data as $word) {
$index = $skills[$index];
$new_data = explode (",", $word);
$content[$index]["rank"] = $new_data[0];
$content[$index]["level"] = $new_data[1];
$content[$index]["experience"] = $new_data[2];
$index++;
}
*/
$stats0 = explode(",", $data[0]);
echo "\n";
echo "\n";
echo "Overall Rank: " .number_format($stats0[0]);
echo "\n";
echo "Total Level: " .number_format($stats0[1]);
echo "\n";
echo "Overall Total XP: " .number_format($stats0[2]);
$stats1 = explode(",", $data[1]);
echo "\n";
echo "\n";
echo "Attack Rank: " .number_format($stats1[0]);
echo "\n";
echo "Attack Level: " .number_format($stats1[1]);
echo "\n";
echo "Attack XP: " .number_format($stats1[2]);
$stats2 = explode(",", $data[2]);
echo "\n";
echo "\n";
echo "Defence Rank: " .number_format($stats2[0]);
echo "\n";
echo "Defence Level: " .number_format($stats2[1]);
echo "\n";
echo "Defence XP: " .number_format($stats2[2]);
?>
Example above should be working when ran you can use this player to see output -- .php?player=zezima
The output of each $data[0] is something like--------53,2496,1661657944
53-----------------------number_format($stats0[0])
2,496--------------------number_format($stats0[1])
1,661,657,944------------number_format($stats0[2])
--
Then I'm trying to break up each $data[] index into 3 pieces, the way I have it above works but I want to be able to do something like a for each loop to go through each $data[] indexes and break each up using explode(",", $data[0]); explode(",", $data[1]); explode(",", $data[2]); but it would have the index increment each time. What I need in the end is each value to be in a variable that I can use. Example:
$apple = number_format($stats0[0]);
echo $apple;
This is what I've tried something with:
$content = array();
foreach ($data as $word) {
$index = $skills[$index];
$new_data = explode (",", $word);
$content[$index]["rank"] = $new_data[0];
$content[$index]["level"] = $new_data[1];
$content[$index]["experience"] = $new_data[2];
$index++;
}
instead of repeating yourself again and again, create a function like this one:
function print($data, $i){
$stats0 = explode(",", $data[$i]);
echo "\n\nOverall Rank: " .number_format($stats0[0]) . "\n";
echo "Total Level: " .number_format($stats0[1]) . "\n";
echo "Overall Total XP: " .number_format($stats0[2]);
}
and call it in a loop.

Write a dot instead of a comma when it's last element in PHP

I have a while loop use to write a list. i'd like every element separated with a comma, but write a dot after the last one, not a coma.
Here is my code
$exec = mysql_query($req);
while ($row = mysql_fetch_assoc($exec)){
echo '<strong>'.$row['name'].'</strong>, ';
}
But I don't know how to do that. I tried using count() or end(), but none of these works. A little help would be great !
$html = array();
$exec = mysql_query($req);
while ($row = mysql_fetch_assoc($exec)){
$html[] = '<strong>' . htmlspecialchars($row['name']) . '</strong>';
// --------------------^^^^^^^^^^^^^^^^! (1)
}
$html = implode(', ', $html) . '.';
(1) - Never output data to HTML without escaping it properly.
I like the use the implode function for this :)
$list = array();
$exec = mysql_query($req);
while ($row = mysql_fetch_assoc($exec)){
$list[] = '<strong>'.$row['name'].'</strong>';
}
$string = implode(", " , $list);
echo $string . ".";
HTH
Try this:
$exec = mysql_query($req);
$output = array();
while ($row = mysql_fetch_assoc($exec)){
$output[] = '<strong>'.$row['name'].'</strong>';
}
echo implode(',', $output), '.';
Build the string but don't output. Then, trim off the command and add a fullstop:
$exec = mysql_query($req);
$output = "";
while ($row = mysql_fetch_assoc($exec))
{
$output .= '<strong>'.htmlentities($row['name']).'</strong>, ';
}
if($output) echo rtrim($output, ', ').".";

Categories