How do I combine all elements in an array using comma? - php

I know this question has with out any doubt been asked a whole lot of times. I though can seem to find a solution. So forgive me if it's way to simple.
The question is how do access the end of a while loop.
E.g.
while($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c = $countByMonth["COUNT(id)"];
echo $c . "," ;
}
How do I manage separate each value of the while loop by a comma but of course I don't want the comma at the end of the value.
In advance thank you very much for your help :)

You can:
1) Build a string, and remove the last character:
$c = '';
while ($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c .= $countByMonth["COUNT(id)"] . ',';
}
$c = substr($c, 0, -1);
echo $c;
2) Build an array and use implode()
$c = array();
while ($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c[] = $countByMonth["COUNT(id)"];
}
echo implode(',', $c);
Tip: You can use aliases in your query, like: SELECT COUNT(id) as count FROM .... Then you can access it as $countByMonth['count'], which looks cleaner IMO.

The simple1 solution:
$isFirst = true;
while($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c = $countByMonth["COUNT(id)"];
if ($isFirst) {
$isFirst = false;
} else {
echo = ', ';
}
echo $c;
}
Alternatively, you could implode() the values. Or - perhaps easier to read/understand/maintain - concatenate it all into a string and remove the last "," (SO eats my whitespace; the string is comma-whitespace):
$list = '';
while($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c = $countByMonth["COUNT(id)"];
$list .= $c . ', ';
}
echo substring($list, 0, -2); // Remove last ', '
(Several other answers propose the use of an accumulated array and then use implode(). From a performance perspective this method will be superior to string concatenation.)
1 See comments.

Alternatively you can do:
$arr = array();
while($countByMonth = mysql_fetch_array($countByMonthSet)) {
$arr[] = $countByMonth["COUNT(id)"];
}
echo implode(', ',$arr);

Or afterwards just trim it off with rtrim($c, ',')

While I think the implode solution is probably best, in situations where you can't use implode, think of the basic algorithm differently. Rather than "how can I add a comma behind every element but the last?" ask yourself "how can I add a comma before every element but the first?"
$str = '';
$count = count( $array );
if( $count ) {
$i = 0;
$str = $array[$i];
$i++;
while( i < $count ) {
$str .= ','.$array[$i];
$i++;
}
}
If you "shift" the first element, then you can use a foreach loop:
$str = '';
if( count( $array ) ) {
$str = array_shift( $array );
foreach( $array as $element ) {
$str .= ', '.$element;
}
}

Ty this:
int count;//
while(i)
{
count=i;
}

Related

How to splitt a string to an array with keys and values using php

I have string and I want to splitt it to array and remove a specific part and then convert it back to a string .
$string = "width,100;height,8600;block,700;narrow,1;"
I want to search block in this string and remove it with its value "block,700;" and get the string as "width,100;height,8600;narrow,1;"
below is my code php which i tried.Please advice me
$outerARR = explode(";", $string);
$arr = array();
foreach ($outerARR as $arrvalue) {
$innerarr = explode(",", $arrvalue);
$arr[] = $innerarr;
}
for ($i = 0; $i < count($arr); $i++) {
if (in_array($arr, 'block')) {
unset($arr[$i]);
}
}
Please note that "block" in aboive string will not always contain and the value may differ. So I can't use string replace . please advice
You essentially want to replace part of your string:
$string = "width,100;height,8600;block,700;narrow,1;";
$regex = '#(block,(.*?);)#';
$result = preg_replace($regex, '', $string);
echo $result;
Try this:
$string = "width,100;height,8600;block,700;narrow,1;"
$outerARR = explode(";", $string);
$arr = array();
foreach ($outerARR as $arrvalue) {
$innerarr = explode(",", $arrvalue);
$arr[$innerarr[0]] = $innerarr[1];
}
if (array_key_exists('block', $arr)) {
unset($arr['block']);
}

Simplify and Abstract my Code: Combining Strings

I want to combine strings in PHP. My script creates every possible combination like below.
$part1 = array('','d','n','s','g');
$part2 = array('a','e','o','oo');
$part3 = array('m','n','s','d','l','t','g','j','p');
$part4 = array('g','p','l','');
$part5 = array('g','p','l');
$part6 = array('a','e','o');
$part7 = array('d','l','r','');
$names = array();
foreach ($part1 as $letter1) {
foreach ($part2 as $letter2) {
foreach ($part3 as $letter3) {
foreach ($part4 as $letter4) {
foreach ($part5 as $letter5) {
foreach ($part6 as $letter6) {
foreach ($part7 as $letter7) {
$names[] = $letter1 . $letter2 . $letter3 . $letter4 . $letter5 . $letter6 . $letter7;
}
}
}
}
}
}
}
But I am not happy with my solution. I is quick and dirty code. Is there a solution wich works with a flexible number of part arrays, so I can extend the script by e.g. $part8 easiely? (without changing the loop construction)
Recursive one:
function buildNames( $parts, $chars = ''){
// Nothing to do, shouldn't happen
if( !count( $parts)){
return array();
}
$names = array();
$part = array_shift( $parts);
// Max level, we can build final names from characters
if( !count( $parts)){
foreach( $part as $char){
$names[] = $chars . $char;
}
return $names;
}
// "We need to go deeper" and build one more level with remembered chars so far
foreach( $part as $char){
$names = array_merge( $names, buildNames( $parts, $chars . $char));
}
return $names;
}
$parts = array( $part1, $part2, $part3, $part4, $part5, $part6, $part7);
$names = buildNames( $parts);
From head, from scratch, comment if something, but idea should be good
You could reduce this problem to six cartesian products:
cartesianProduct($part1,
cartesianProduct($part2,
cartesianProduct($part3,
cartesianProduct($part4,
cartesianProduct($part5,
cartesianProduct($part6, $part7))))));
function cartesianProduct($p1, $p2) {
$ret = array();
foreach($p1 as $l1)
foreach($p2 as $l2)
$ret[] = $l1 . $l2;
return $ret;
}

Remove Last String if its ', '

i have string like this
$string = 'aaaaaa, bbbbbb, cccccc, ';
and i want to modified it to be like this
$string = 'aaaaaa, bbbbbb, cccccc';
the last ',' and space is removed.
how to do this in php?
what is the function needed the achieve that?
my full code is like this
if(isset($_POST['accomodation'])) $accomodation = 'Accomodation, ';
if(isset($_POST['dance'])) $dance = 'Dance Lessons, ';
if(isset($_POST['vacation'])) $vacation = 'Vacation planning, ';
if(isset($_POST['group'])) $group = 'Group Vacation, ';
if(isset($_POST['inprivate'])) $inprivate = 'Private Vacation, ';
if(isset($_POST['land'])) $land = 'Land purchase/lease';
if(isset($_POST['all'])) $all = 'All';
#$interest = $accomodation.$dance.$vacation.$group.$inprivate.$land;
#echo $string;
*sorry for such dumb question, it's been so long i didn't touch native PHP programming
rtrim() function:
rtrim($string,', ');
but how are you defining the string? It may be that you can build it without the comma and space.
EDIT
$interests = array();
if(isset($_POST['accomodation'])) $interests[] = 'Accomodation';
if(isset($_POST['dance'])) $interests[] = 'Dance Lessons';
if(isset($_POST['vacation'])) $interests[] = 'Vacation planning';
if(isset($_POST['group'])) $interests[] = 'Group Vacation';
if(isset($_POST['inprivate'])) $interests[] = 'Private Vacation';
if(isset($_POST['land'])) $interests[] = 'Land purchase/lease';
if(isset($_POST['all'])) $all = 'All';
$interest = implode(', ',$interests);
echo $interest;
$string = preg_replace('/\s*,\s*$/', '', $string);
or, way cooler:
$string = rtrim($string, " ,");
Note that it does not matter the order of the characters in the pattern string.
#You last update.
This changes some things. You could put all your variables in one array and then implode it. Like so:
$items = array();
$items[] = $accomodation = 'Accomodation';
$items[] = $dance = 'Accomodation';
...
$result = implode(', ', $items)
$string = preg_replace( "/,\s*$/","",$string);
Should do the trick
Is it always a comma then a space at the end?
substr($string, 0, -2)
Often times, you can avoid the trailing comma altogether by changing the way you build the string. For example:
$count = 0;
foreach ($this as $that) {
if ($count != 0) {
$string .= ',';
}
$string .= $that['stuff'];
$count++;
}
Would remove the possibility of any trailing comma at the end, no matter the combination of results.

refactoring and using a counter?

I have the following structure:
$text_1 = $this->getValue('value_1');
$text_2 = $this->getValue('value_2');
$text_3 = $this->getValue('value_3')
And also the following:
foreach($text_1 as $t_1)
{
if(!$first)
{
$string_1 .= ",";
}
$first = false;
$string_1 .= $t_1;
}
foreach($text_2 as $t_2)
{
if(!$first)
{
$string_2 .= ",";
}
$first = false;
$string_2 .= $t_2;
}
foreach($text_3 as $t_3)
{
if(!$first)
{
$string_3 .= ",";
}
$first = false;
$string_3 .= $t_3;
}
I was wondering if this could be re-factored to use a counter, like in a for loop, to replace the _1, _2, _3 etc from my code?
Well, the foreach-loops can be replaced with implode.
Other than that, wouldn't it be better to use an array for your $text_?? variables? Eg.:
$text = $this->getValue('value');
foreach ($text as $value) {
$strings[] = implode(",", $value);
}
Hard to give more concrete advise, without the exact context, but that should get you in the right direction.
I hope this one helps u...
$arrOutput = compact('text_1', 'text_2', 'text_3');
foreach($arrOutput as $t1)
{
$out1[] = implode(",", $t1);
}
print_r($out1);
Yes, you should probably be using an array or map to hold the values and iterating over that, assuming that the values you're dealing with are all the same sort of thing.
Ok so I figured out a way of doing it:
for ($i=1;$i<=12;$i++) {
$choices = $this->getValue('question_'.$i);
$serialized = "";
$first = true;
foreach($choices as $choice)
{
if(!$first)
{
$serialized .= ",";
}
$first = false;
$serialized .= $choice;
}
$this->setValue('question_'.$i, $serialized);
}
This seems to work well!

Stacking a variable in reverse in PHP

I have a loop spitting out values and are put into a string:
$all_values = "";
while loop {
$value = "...";
$all_values .= $value . ",";
}
Output: 1,3,8,2,10...
What's the simplest way to output the same thing but numbers in reverse so the above example would come out like ...10,2,8,3,1
Put everything into an array and then join it together, reversed:
$all_values = array();
while loop {
$value = "...";
$all_values[] = $value;
}
$all_values = implode(',', array_reverse($all_values));
This is also more efficient if there are millions of values.
Add after your code:
$ar = explode(',', $all_values);
$revAr = array_reverse($ar);
$all_values = implode(',', $revAr);

Categories