Build comma separated string in PHP Loop - php

Hello Guys i need to do this,
I have a common loop
foreach ($stuffs as $stuff) {
echo $stuff;
}
Lets assume $stuff is an 'id' of a mysql table what i have and i dont want to be showed in next results, so i want to build a string like this
1,23,54,67 (comma separated)
So that string will be in mysql query to exclude results that already have been shown.
how can i do that?
Should be with implode? How can i achieve that?

implode should be the tool:
implode(",", $stuffs);
will return a comma separated list.
Test
$myarray=array(1,2,"hello",4,5);
echo implode(",", $myarray);
returns
1,2,hello,4,5

If you really wanna have the loop:
$values = "";
foreach ($stuffs as $stuff) {
$values != "" && $values .= ",";
$values .= $stuff;
}
echo $values;
I suggest using implode, but the loop can really give you more power if you wanna do some further stuff.

This worked in my case (detects if isn't the loop last iteration):
foreach($array as $key => $val){
...
if($key!==count($array)-1){echo ',';}
}

Should be as simple as:
$string = implode(",",$stuffs);
echo $string

Related

Counting multidimensional array rows and their respective elements?

I'm doing something that is perhaps too long and strange to explain, but basically I've mapped a string in a complex way into an array in a way to make them jumbled up. This is an example of how it would look:
field[26][25]='x';
field[24][23]='z';
field[28][29]='y';
Now that I've successfully jumbled up the string in exactly the way I wanted, I need to reconstruct the linear result.
So I need to take row 1 of the array, and loop through all the elements in this row to combine them into a string. Then do the same thing with row 2 and so on to create one massive linear string.
How do I count how many rows and elements in those rows I have? For the life of me I cant even begin to find how to do this for multid arrays.
Kind regards
#u_mulder's got a solid answer there. For the number of elements, you'd just say:
$total = 0;
foreach( $matrix as $row ) $total += count($row);
For the concatenation of elements, you'd just say:
$concat = '';
foreach( $matrix as $row ) $concat .= implode('', $row);
Bob's your uncle. But really, is there a valid use case for such a strange mashup?
$field[26][25]='x';
$field[24][23]='z';
$field[28][29]='y';
$field_string = '';
array_walk_recursive ( $field , function($item, $key) use (&$field_string){
if(!is_array($item)){
$field_string .= $item;
}
});
echo $field_string;
Honestly, this is a little confusing. I may need more info but let me know if this helps
You can start with an empty string and use two nested foreach to iterate over lines and items on each line and append each item to the string:
$result = '';
foreach ($fields as $row) {
foreach ($row as $item) {
$result .= $item;
}
}
Or you can replace the entire inner foreach with $result .= implode('', $row);.
You can even replace the outer foreach with a call to array_map() then implode() the array produced by array_map() into a string:
$string = implode(
'',
array_map(
function (array $items) {
return implode('', $items);
},
$fields
)
);

How to merge multiple arrays in array without duplicates

I am a newbie in this and I have read lots of stuff about this matter (including some topics here), before starting this topic, but I do not quite get it yet, so I will ask for some help (if it is possible) :)
So, in the column that I want to print I have values like this on every row:
value1|value2|value5|value12|value25
value3|value5|value12|value14|value26|value32|value55
value1|value2|value14|value26|value31
The number of rows can be 3 or 1500+... So I want to merge the arrays and print those values sorted and without duplicates: value1, value2, value3, value5, value12, etc...
I have tried to explode the arrays, but I could not find out how to assign a variable to every array and merge them and all I have done is to print all values:
foreach ($rows as $areas) {
foreach (explode('|', $areas->value) as $area) {
var_dump($area);
}
}
Afterwards I have read somewhere this will be very slow if I have many rows (and I am going to have thousands), so I am stuck here and I do not know what else I could do...
I will appreciate any help and direction that you can give me, because it is too hard for me and I can not do it without help
Thank you in advance
You can store each value of your exploded string as key (if it's not an object nor array), it store only unique values. Then you have to just use array_keys() to get keys and sort returned array:
$rows = array(
'value1|value2|value5|value12|value25',
'value3|value5|value12|value14|value26|value32|value55',
'value1|value2|value14|value26|value31'
);
$results = array();
foreach ($rows as $row) {
$items = explode('|', $row);
foreach ($items as $item) {
$results[$item] = 0;
}
}
$results = array_keys($results);
sort($results, SORT_NATURAL);
Live demo on eval.in
There are two ways of doing this:
<?php
$str = 'value1|value2|value5|value12|value25';
$str1 = 'value3|value5|value12|value14|value26|value32|value55';
$str2 = 'value1|value2|value14|value26|value31';
//-- Method 1: Concat and make a single string and then explode and make a single array
$finalString = $str . '|' . $str1 . '|' . $str2;
print_r(array_unique(explode('|', $finalString)));
//-- Method 2: explode first and then merge into a single array
$strArr = explode('|', $str);
$strArr1 = explode('|', $str1);
$strArr2 = explode('|', $str2);
print_r(array_unique(array_merge($strArr, $strArr1, $strArr2)));

make the data into an array and get the values

I have the data in my table like this
Arabic,Assamese,Azerbaijani,Belarusian
I want to show the data in an array so that I can use foreach and get the values for the array. So can someone tell me how to make it as an array and get values?
$string = "Arabic,Assamese,Azerbaijani,Belarusian";
$language_array= explode(',',$string);
Supposing you have perform the query to the database and already has the data you can use explode function. See this DEMO.
$data = $row['data_from_table']; //your data is Arabic,Assamese,Azerbaijani,Belarusian
$exp = explode(",", $data);
foreach ($exp as $value){
echo $value;
echo PHP_EOL;
}
?>
Use explode function
$database_value = $db['your_data'];
$value_array = explode(',',$database_value);
print_r($value_array);
foreach ($value_array as $value){
echo $value.'<br>';
}

Grabbing array from database, then getting information using each array value

totally stumped in this, basically I'm getting a comma seperated list from a user table, using it as an array and then using each value in the array to fetch data from a different table and output then.
$award_array = array($user_class->awards);
foreach($award_array as $award) {
$getaward = mysql_query("SELECT `name`, `text`, `image` FROM `awards_av` WHERE `id` = '".$award."'");
$awardstuff = mysql_fetch_array($getaward);
echo "<img src='".$awardstuff['image']."' alt='".$awardstuff['name']."' title='".$awardstuff['text']."' />";
}
This is only giving out the first number in the array ($user_class->awards in this case is 1,2,3,4,5,6)
Any help is much appreciated!
I think I see the problem. You cannot simply take a string of a comma separated list, and throw it inside an array() tag and expect it to automatically convert it to an array. You must use the explode() function to do that.
What you're trying to do:
<?php
$string = 'a,b,c,d,e';
$myarray = array($string);
foreach ($myarray as $k => $v) {
print $v .'<br />';
}
?>
Except that doesn't work. You need to convert the comma-separated list of values (which is a string) into an array, but you don't use array() to do that. You use PHP's built-in function called explode() -> http://php.net/explode like this...
<?php
$string = 'a,b,c,d,e';
$myarray = explode(',' $string);
foreach ($myarray as $k => $v) {
print $v .'<br />';
}
?>
I think that is the problem you're having

Array a string in the following format?

How can i array a string, in the format that $_POST does... kind of, well i have this kind of format coming in:
101=1&2020=2&303=3
(Incase your wondering, its the result of jQuery Sortable Serialize...
I want to run an SQL statement to update a field with the RIGHT side of the = sign, where its the left side of the equal sign? I know the SQL for this, but i wanted to put it in a format that i could use the foreach($VAR as $key=>$value) and build an sql statement from that.. as i dont know how many 101=1 there will be?
I just want to explode this in a way that $key = 101 and $value = 1
Sounds confusing ;)
Thanks so so much in advanced!!
See the parse_str function.
It's not the most intuitive function name in PHP but the function you're looking for is parse_str(). You can use it like this:
$myArray = array();
parse_str('101=1&2020=2&303=3', $myArray);
print_r($myArray);
One quick and dirty solution:
<?php
$str = "101=1&2020=2&303=3";
$VAR = array();
foreach(explode('&', $str) AS $pair)
{
list($key, $value) = each(explode('=', $pair));
$VAR[$key] = $value;
}
?>
parse_str($query_string, $array_to_hold_values);
$input = "101=1&2020=2&303=3";
$output = array();
$exp = explode('&',$input);
foreach($exp as $e){
$pair = explode("=",$e);
$output[$pair[0]] = $pair[1];
}
Explode on the & to get an array that contains [ 101=1 , 2020=2 , 303=3 ] then for each element, split on the = and push the key/value pair onto a new array.

Categories