I have a foreach loop. which has a variable. how to store variable values in a single variable separated by comma,
foreach($variable as $key => $value){
$variable = $value->Id;
}
Do not use the same name of variable already used.
$otherV = '';
foreach($variable as $key => $value){
if ($otherV) $otherV .= ',';
$otherV .= $value->Id;
}
Use php implode() function:
$str = implode(',',$array);
See on php.net http://php.net/manual/en/function.implode.php
If your $variable is Object, first convert it to array with get_object_vars()
Related
<?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 an array holding this data:
Array (
[1402377] => 7
[1562441] => 7
[1639491] => 9
[1256074] => 10
)
How can create a string that contains the keys of the above array?
Essentially, I need to create a comma separated string that consists of an array's keys
The string would look like: 'key','key','key'
Do I need to create a new array consisting of the keys from an existing array?
The reason I need to do this is because I will be querying a MySQL database using a WHERE in () statement. I would rather not have to query the database using a foreach statement. Am I approaching this problem correctly?
I've tried using a while statement, and I'm able to print the array keys that I need, but I need those keys to be an array in order to send to my model.
The code that allowed me to print the array keys looks like this:
while($element = current($array)) {
$x = key($array)."\n";
echo $x;
next($array);
}
$string = implode(',', array_keys($array));
By the way, for looping over an array consider not using current and next but use foreach:
foreach ($array as $key => $value) {
//do something
}
This will automatically iterate over the array until all records have been visited (or not at all if there are no records.
$keys = array_keys($array);
$string = implode(' ',$keys);
In your case, were you are using the result in a IN clause you should do:
$string = implode(',', $keys);
$yourString = '';
foreach($yourArr as $key => $val) {
$yourString .=$key.",";
}
echo rtrim($yourString, ",");
//OR
$yourString = implode(",", array_keys($yourArray));
See : array_keys
implode(', ', array_keys($array));
Use php array_keys and implode methods
print implode(PHP_EOL, array_keys($element))
The string would look like: 'key','key','key'
$string = '\'' . implode('\',\'', array_keys($array)) . '\'';
Imploding the arguments and interpolating the result into the query can cause an injection vulnerability. Instead, create a prepared statement by repeating a string of parameter placeholders.
$paramList = '(' . str_repeat('?, ', count($array) - 1) . '?)'
$args = array_keys($array);
$statement = 'SELECT ... WHERE column IN ' . $paramList;
$query = $db->prepare($statement);
$query->execute($args);
I have an array of strings and I need to build a string of values separated by some
character like comma
$tags;
implode()
There is a simple function called implode.
$string = implode(';', $array);
You should use the implode function.
For example, implode(' ',$tags); will place a space between each item in the array.
If any one do not want to use implode so you can also use following function:
function my_implode($separator,$array){
$temp = '';
foreach($array as $key=>$item){
$temp .= $item;
if($key != sizeof($array)-1){
$temp .= $separator ;
}
}//end of the foreach loop
return $temp;
}//end of the function
$array = array("One", "Two", "Three","Four");
$str = my_implode('-',$array);
echo $str;
There is also an function join which is an alias of implode.
Using implode
$array_items = ['one','two','three','four'];
$string_from_array = implode(',', $array_items);
echo $string_from_array;
//output: one,two,three,four
Using join (alias of implode)
$array_items = ['one','two','three','four'];
$string_from_array = join(',', $array_items);
echo $string_from_array;
//output: one,two,three,four
I have a loop like
foreach ($_GET as $name => $value) {
echo "$value\n";
}
And I want to add a comma in between each item so it ends up like this.
var1, var2, var3
Since I am using foreach I have no way to tell what iteration number I am on.
How could I do that?
Just build your output with your foreach and then implode that array and output the result :
$out = array();
foreach ($_GET as $name => $value) {
array_push($out, "$name: $value");
}
echo implode(', ', $out);
Like this:
$total = count($_GET);
$i=0;
foreach ($_GET as $name => $value) {
$i++;
echo "$name: $value";
if ($i != $total) echo', ';
}
Explained: you find the total count of all values by count(). When running the foreach() loop, you count the iterations. Inside the loop you tell it to echo ', ' when the iteration isn't last (isn't equal to total count of all values).
$comma_separated = implode(", ", $_GET);
echo $comma_separated;
you can use implode and achieve that
You could also do it this way:
$output = '';
foreach ($_GET as $name => $value) {
$output = $output."$name: $value, ";
}
$output = substr($output, 0, -2);
Which just makes one huge string that you can output. Different methods for different styles, really.
Sorry I did not state my question properly.
The awnser that worked for me is
implode(', ', $_GET);
Thanks, giodamelio
I'd typically do something like this (pseudo code):
myVar
for... {
myVar = i + ","
}
myVar = trimOffLastCharacter(myVar)
echo myVar
How do I go about setting a string as a literal variable in PHP? Basically I have an array like
$data['setting'] = "thevalue";
and I want to convert that 'setting' to $setting so that $setting becomes "thevalue".
Thanks for any help!
See PHP variable variables.
Your question isn't completely clear but maybe you want something like this:
//Takes an associative array and creates variables named after
//its keys
foreach ($data as $key => $value) {
$$key = $value;
}
extract() will take the keys of an array and turn them into variables with the corresponding value in the array.
${'setting'} = "thevalue";
It may be evil, but there is always eval.
$str = "setting";
$val = "thevalue";
eval("$" . $str . " = '" . $val . "'");