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>";
}
?>
<?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.
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 [];
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);
}
?>
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/>";
}