php multi level foreach loop remove last comma from loop - php

hii i have 2 level foreach loop like this and i want to remove last comma from each loop ,
/* Here is the mysql query */
foreach($loop1 as $val1){
$showvalone = $val1['data1'];
echo "[".$showvalone;
/* Here is the second MySQL query connected with 1st query */
foreach($loop2 as $val2){
$showvaltwo[] = $val2['data2'];
}
echo implode(",",$showvaltwo);
echo "] , ";
}
output of this program :
[ 1
one ,
two ,
three
],
[ 2
one ,
two ,
three
],
And i want like this
[ 1
one ,
two ,
three
],
[ 2
one ,
two ,
three
]
i am already use implode , trim but is remove only one loop not remove second .
sol me my problem , thanks .

You can turn the problem around and add the ',' to the start of the next output. There is no need to remove it afterwards.
However you don't want the comma for the first output.
$addComma = ''; // should be empty for the first lines.
foreach($loop1 as $val1){
$showvalone = $val1['data1'];
echo $addComma."[".$showvalone;
/* Here is the second MySQL query connected with 1st query */
foreach($loop2 as $val2){
$showvaltwo[] = $val2['data2'];
}
echo implode(",",$showvaltwo);
echo "]";
$addComma = " , "; // any lines following will finish off this output
}

Rather than output the information directly you could put it in to a variable as a string. This will allow you to rtrim the last comma after the loop, then echo the information.
// Declare variable to hold the string of information.
$values = "";
/* Here is the mysql query */
foreach($loop1 as $val1)
{
$showvalone = $val1['data1'];
$values .= "[".$showvalone;
/* Here is the second MySQL query connected with 1st query */
foreach($loop2 as $val2)
{
$showvaltwo[] = $val2['data2'];
}
$values .= implode(",",$showvaltwo);
$values .= "] , ";
}
// Remove the last comma and spaces from the string.
$values = rtrim($values, ' , ');
// Output the information.
echo $values;

I have my own version in removing "," at the end and instead of adding a "."
$numbers = array(4,8,15,16,23,42);
/* defining first the "." in the last sentence instead of ",". In preparation for the foreach loop */
$last_key = end($ages);
// calling the arrays with "," for each array.
foreach ($ages as $key) :
if ($key === $last_key) {
continue; // here's the "," ends and last number deleted.
}
echo $key . ", ";
endforeach;
echo end($ages) . '.' ; // adding the "." on the last array

Related

PHP New Line after n commas

I want to insert a new line after n commas.
For example I got this value: 385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426
How I could echo them all, but every 5th comma there should be a linebreak?
385,386,387,388,389,
390,391,392,393,394,
395,396,397,398,399,
400,401,402,403,404,
405,406,407,408,409,
410,411,412,413,414,
415,416,417,418,419,
420,421,422,423,424,
425,426
Here's one method:
// Get all numbers
$numbers = explode(',', $str);
// Split into groups of 5 (n)
$lines = array_chunk($numbers, 5);
// Format each line as comma delimited
$formattedLines = array_map(function ($row) { return implode(',', $row); }, $lines);
// Format groups into new lines with commas at the end of each line (except the last)
$output = implode(",\n", $formattedLines);
Try this
<?php
//Start //Add this code if your values in string like that
$string = "385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426";
$string_array = explode(',', $string);
//End //Add this code if your values in string like that
//If you have values in array then direct use below code skip above code and replace $string_array variable with yours
end($string_array);
$last = key($string_array);
foreach ($string_array as $key => $value) {
if($last==$key){
echo $value;
}else{
echo $value.',';
}
if(($key+1)%5==0){
echo "<br />";
}
}
?>
Try like this.
You can explode the string with commas and check for every 5th
position there should be a line break.
You can check it with dividing key with 5.(i.e) it will give you a
remainder of 0
Please note that key starts from 0, so I have added (key+1), to make it start from 1
$string = "385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426";
$stringexplode = explode(",", $string);
$countstringexplode = count($stringexplode);
foreach($stringexplode as $key => $val)
{
$keyIncrement = $key+1;
echo $val.($countstringexplode == $keyIncrement ? "" : ",") ;
if(($keyIncrement) % 5 == 0)
echo "<br>";
}
?>

Foreach loop with Concatenation assignment

<?php
$names =array('Alex','Billy','Tabby');
$names_str=null;
foreach($names as $key => $names)
{
$names_str .= $name;
if(key!= (count($names)-1))
{
$names_str.=', ';
}
}
echo $names_str;
?>
why do we set names_str=null?
why do we put count($names-1)) how does this loop work?
<?php
$names = array('Alex','Billy','Tabby');
$names_str = null;
foreach($names as $key => $names)
{
$names_str .= $name;
if(key != (count($names) - 1))
{
$names_str .=', ';
}
}
echo $names_str;
?>
Why do we set $names_str = null?
It is being initialized outside of the loop. If this is a string to be returned, technically doing $names_str = ""; would work better if you want a default value to show and aren't doing some sort of empty/null check...
Why do we put count($names-1))?
This checks the key # e.g. (0,1,2) against the count/length of the array minus 1 (array starts at 0), to see if we are referencing the last key/value pair in the array, to determine if the string should show a comma between the current value and next value, or not. If it's the last value, we don't want to show a "," at the end of the string.
How does this loop work?
$names_str .= $name; concatenates the $name values to the initial string, with the if/key check placing commas between each value. See above about the count. So you end up with "Alex, Billy, Tabby" as the final value for $names_str.
A better way to do this is to use PHP's implode function:
$comma_separated = implode(",", $names);
This would give you the same comma separated list.

Php array in a foreach loop

I have been trying to create a Multidimensional array from an already existing array. The reason I am doing this is so I can separate the super array into a more categorized version so that later on I can run foreach on just those categories in another script.
This is a snippet of code // Please read comments :)
$and = array();
if($this-> input-> post('and')) // This is the super array and[] from a previous input field
{
if(preg_grep("/reason_/", $this-> input-> post('and'))) // Search for the reason_
{
foreach($this-> input-> post('and') as $value) // if reason_ is present
{
$and['reason_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then i would get only values like 1, 2, 3, 4, and then concatenate them to the index
}
}
if(preg_grep("/status_/", $this-> input-> post('and'))) // Search for status
{
foreach($this-> input-> post('and') as $value) // If it is in the super array
{
$and['status_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then I would get values again like 1,2,3,4,5 and then concatenate them to the index
}
}
}
This approach is not giving me expected outcome however, I am getting a big string like so :
array(2) { ["reason_and"]=> string(24) "2 , 3 , 4 , 3 , 4 , 5 , "
["status_and"]=> string(24) "2 , 3 , 4 , 3 , 4 , 5 , "
So to my knowledge (which is limited) when I try to do a foreach over the array
[reason_and]
I only get one loop since the array ["reason_and] only has one value (the 24 character string?). Is it possible to have the reason_and have a value for each of the numbers?
Is this even possible? I'm quite confused.
I've referred to this question for reference but I still do not get a outcome that I can work with. Thanks in advance.
This
$and['reason_and'] .= end(explode('_', $value)) . ' , ';
^^^^----
should be
$and['reason_and'][] = end(explode('_', $value)) . ' , ';
^^--
which turns it into an "array push" operation, not a string concatenation. Then 'reason_and' will be an array, and you foreach over it.
first of all preg_grep returns an array with matched values, so
$andArray = $this-> input-> post('and'); // This is the super array and[] from a previous input field
if($andArray) {
$reason = preg_grep("/reason_/", $andArray); // Search for the reason_
if($reason) { // if reason_ is present
foreach($reason as $value) {
$and['reason_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then i would get only values like 1, 2, 3, 4, and then concatenate them to the index
}
}
$status = preg_grep("/status_/", $andArray); // Search for status
if($status) {
foreach($status as $value){ // If it is in the super array
$and['status_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then I would get values again like 1,2,3,4,5 and then concatenate them to the index
}
}
}
Or if you need result as array, then remove ' , ' and replace dot with [];

PHP MySQL check if request have ' # ' char insert a new row

I Have some request like below :
$input = "$POS,1234,5223,A,2719";
If get a request like above , process an save to database with below code :
$input_ex = explode(",", $input);
$input_ex[0];
$input_ex[1];
$input_ex[2];
$input_ex[3];
$input_ex[4];
mysql_query("INSERT INTO table_name (cl_1,cl_2,cl_3,cl_4,cl_5)
values ('$input_ex[0]','$input_ex[1]','$input_ex[2]','$input_ex[3]','$input_ex[4]')
Problem:
my inputs may be sometimes more than one and split with ' # ' character
last row of inputs is maybe have ' # ' character too
$input = "$POS,1234,5223,A,2719#
$POX,752,4342,N,SXD#
$POZ,122,6242,B,XFB#";
How can i separate each row and insert it on database as a new row ?
thanks ;)
edit :
inputs is 3 different mode , 1st is a one row without any # sign , 2nd is have more row with end # on last row , 3th more row without # sign on end of last row
foreach (explode('#', $input) as $record) {
$record = trim($record);
if ($record == '')
continue;
$input_ex = explode(',', $record);
$input_ex[0];
$input_ex[1];
$input_ex[2];
$input_ex[3];
$input_ex[4];
// Same MySQL query as you already have
mysql_query("...");
}
first explode by '#', and for each result explode by ',' and add new row
Just explode on the '#" first, then loop through the array of results exploding on "," as you are doing and making an insert for each row.
You will need to use explode() twice. First to check for multiple records and then once more to split on the delimiter ,:
<?php
$input = "POS,1234,5223,A,2719# POX,752,4342,N,SXD# POZ,122,6242,B,XFB#";
foreach(explode('#', $input) as $records){
$record = explode(',', $records);
print_r($record);
}
?>

Separating certain keys from an Array into two clearly distinct groups. How?

I would like to add stuff out of an array and translate them. However, some items in the array I do not want to translate and so encapsulate them into special tags. In this example i've uset < > but if you have suggestions/better iead's I'm open to them. I also thought of { } or [ ] and * * whichever you think is easiest.
<?php
# define the contents of my all time clients
$clients = array('<UNESCO>', 'Vrije Universiteit medical center');
# randomization engine
$keys = array_rand($clients, 3); // get 3 random keys from your array
foreach ($keys as $key) { // cycle through the keys to get the values
# if this item is inbetween < > tags..
if #??#######??########??#########??########??##
# then put this item directly into randomList without translation
$randomList .= "• " . $clients[$key]) . "<br/>"; // WORKS
# all other items without <tags> are first translated via __() then added
else $randomList .= "• " . __($clients[$key]) . "<br/>"; // WORKS
}?>
Question: What should be on line 10 to make the IF statement complete?
In other words, what is the logic in programming code that can match an item in the array being one of those special words that should not be translated and treaded differently?
Few possible solutions:
if (preg_match('~^<.*>$~', $clients[$key]))
if (strlen($clients[$key]) > 0 && $clients[$key][0] == '<' && substr($clients[$key], -1) == '>')
You probably want to ditch the brackets before outputting the name. You could use this then:
// note that you need to test against $clients[ $key ], not $key
if( preg_match( '~^<(.*)>$~', $clients[ $key ], $matches ) )
{
$randomList .= "• " . $matches[ 1 ] . "<br/>";
}

Categories