This question already has answers here:
PHP Implode wrap in tags
(3 answers)
Closed 11 months ago.
I'd like to create a string variable from an array.
Here's a non working code for conceptualizing it:
$list = array('elem1', 'elem2', 'elem3', 'elem4');
$myString = foreach ( $list as $element ){
'<span>' . $element . '</span><span>|</span>';
};
You can do something like this
<?php
$lists = array("elem1", "elem2", "elem3", "elem4");
$string = '';
foreach ($lists as $element){
$string = $string . ' | '. $element;
};
echo '<span>' . $string . '</span>';
?>
$list = array('elem1', 'elem2', 'elem3', 'elem4');
foreach( $list as $element ){
$myString[] = '<span>' . $element . '</span><span>|</span>';
}
print(implode('', $myString));
What you could do is concatenate the results of each iteration of your loop to a variable that exists outside of the loop.
Example:
$list = array('elem1', 'elem2', 'elem3', 'elem4');
$myString = '';
foreach ( $list as $element ){
$myString .= $myString . '<span>' . $element . '</span><span>|</span>';
};
print($myString);
Related
This question already has answers here:
creating variable name by concatenating strings in php
(4 answers)
Closed 8 years ago.
Simple question, with im sure a simple answer, I just cant get it working!!
I have a function which will be passed one of 5 id's (for example "first", "second", ",third", "fourth" and "fifth").
Inside this function I want to refer to an array whose name is the id followed by _array (for example "first_array", "second_array" etc...)
How do I concatenate the id name passed to the function with the string "_array" ? I know how to do this in a string but not when referring to another variable!
To sum up i will have:
$i_d = "first" //passed to my function
$string = "_array"
and I want to link to an array called:
$first_array
EDIT
My code is the following:
$option_timescale = array ( "1"=>"Immediately",
"2"=>"1 Month",
"3"=>"2 Months",
"4"=>"3 Months",
"5"=>"4 Months",
"6"=>"5 Months",
"7"=>"6 Months",
"8"=>"No Timescale"
);
$option_bus_route = array ( "1"=>"1 minute walk",
"2"=>"5 minute walk",
"3"=>"10 minute walk",
"4"=>"No Bus Needed"
);
$option_train_stat = array( "1"=>"5 minute walk",
"2"=>"10 minute walk",
"3"=>"5 minute drive",
"4"=>"10 minute drive",
"5"=>"No Train Needed"
);
function select_box($k,$v){ //$k is the id and $v is the description for the select boxes label
$string = "option_"; //these two lines
$option_array =$string . $k; //are the troublemakers!
$buffer = '<select name="' . $k . '" id="' . $k . '">';
foreach ($option_array as $num=>$desc){
$buffer .= '<option value="' . $num . '">' . $desc . '</option>';
}//end foreach
$buffer .= '</select>';
$buffer .= '<label for="' . $k . '">' . $v . '</label>';
return $buffer;
}//end function
And the code which calls this function is:
function create_table($titles, $id) { //$titles is the relevant array from lists.php, $id is the id of the containing div
$select = array('timescale','bus_route','train_stat'); //'select' id list
$textarea = array('notes'); // 'textarea' id list
$buffer = '<div id="' . $id . '">';
foreach ($titles as $k=>$v) { //$k is the database/id/name $v is the description text
if (in_array($k,$select)){
$buffer .= select_box($k,$v);
}
else if (in_array($k,$textarea)){
$buffer .= text_box($k,$v);
}
else{
$buffer .= check_box($k,$v);
}
}
$buffer .= '</div>';
echo $buffer;
}
Add $ to eval the string.
$i_d = "first";
$string = "_array";
$myvar = $i_d . $string;
$$myvar = array('one','two','three');
print_r( $$myvar);
I am trying to take a string like...
php,mysql,css
and turn it into .. #php #mysql #css
What I have so far...
$hashTagStr = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);
foreach($hashTags as $k => $v){
$hashTagsStr = '';
$hashTagsStr .= '#'.$v.' ';
}
echo $hashTagsStr;
?>
Problem is it only prints #css
How about this:
$hashTagStr = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);
$hashTagStr = '#' . implode( ' #', $hashTags );
...or:
$hashTagStr = "php,mysql,css";
$hashTagStr = '#' . str_replace( ',', ' #', $hashTagStr );
That's because every time the loop runs you're clearing out $hashTagsStr by doing:
$hashTagsStr = '';
Change it to:
$hashTagStr = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);
$hashTagsStr = '';
foreach($hashTags as $k => $v){
$hashTagsStr .= '#'.$v.' ';
}
echo $hashTagsStr;
Pass your values by reference:
$hashTags = array("php","mysql","css");
foreach ( $hashTags as &$v ) $v = "#" . $v;
Then hammer out the results:
// #php #mysql #css
echo implode( " ", $hashTags );
Demo: http://codepad.org/zbtLF5Pk
Let's examine what you're doing:
// You start with a string, all good.
$hashTagStr = "php,mysql,css";
// Blow it apart into an array - awesome!
$hashTags = explode( "," , $hashTagStr );
// Yeah, let's cycle this badboy!
foreach($hashTags as $k => $v) {
// Iteration 1: Yeah, empty strings!
// Iteration 2: Yeah, empty...wait, OMG!
$hashTagsStr = '';
// Concat onto an empty var
$hashTagsStr .= '#'.$v.' ';
}
// Show our final output
echo $hashTagsStr;
looks like a Job for array_walk
$hashTagStr = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);
array_walk($hashTags, function(&$value){ $value = "#" . $value ;} );
var_dump(implode(" ", $hashTags));
Output
string '#php #mysql #css' (length=16)
You should move the $hashTagsStr = '' line outsite the foreach loop, otherwise you reset it each time
You are defining the variable $hashTagsStrinside the loop.
<?php
$hashTagStr = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);
$hashTagsStr = '';
foreach($hashTags as $k => $v){
$hashTagsStr .= '#'.$v.' ';
}
echo $hashTagsStr;
Anyway, I think this would be simpler:
<?php
$hashTagStr = "php,mysql,css";
$hashTagStr = '#' . str_replace(',', ' #', $hashTagStr);
echo $hashTagStr;
During each iteration of the loop, you are doing $hashTagsStr = '';. This is setting the variable to '', and then appending the current tag. So, when it's done, $hashTagsStr will only contain the last tag.
Also, a loop seems like too much work here, you can much easier just replace the , with #. No need to break it into an aray, no need to loop. Try this:
$hashTagStr = "php,mysql,css";
$hashTagStr = '#'.str_replace(',', ' #', $hashTagStr);
function prepend( $pre, $array )
{
return array_map(
function($t) use ($pre) { return $pre.$t; }, $array
);
}
What you semantically have in your string is an array. ➪ So better explode as soon as possible, and keep working with your array, as long as possible.
Closures & anonymous functions as shown work in PHP 5.4+.
I have a variable on my page called, $recipe['ingredients'];
inside the var you have as follows,
100ml milk, 350ml double cream, 150ml water
and so on. Now I'm trying to split it up so it looks as follows
<ul>
<li>100ml milk</li>
<li>350ml double cream</li>
<li>150ml water</li>
</ul>
So far I have the following code,
$ingredientsParts = explode(',', $row_rs_recipes['ingredients']);
$ingredients = array($ingredientsParts);
while (! $ingredients) {
echo" <li>$ingredients</li>";
}
But for some reason it doesn't work and I do not have the experience with explode to fix it.
$ingredientsParts = explode(',', $row_rs_recipes['ingredients']);
$li = '<ul>';
foreach($ingredientsParts as $key=>$value){
$li.=" <li>$value</li>";
}
$li.= '</ul>';
echo $li;
this should be enough:
$ingredientsParts = explode(', ', $row_rs_recipes['ingredients']);
foreach ($ingredientsParts as $ingredient)
{
echo "<li>$ingredient</li>";
}
or you can explode it by ',' and use echo '<li>' . trim($ingredient) . '</li>'; to remove whitespace from beginning/end of that string
When you explode() a string it is automatically converted into an array. You do not need to convert it to an array type as you did on the second line.
You want to use a foreach() loop to iterate through an array, not a while loop.
$ingredientsAry = explode(',', $row_rs_recipes['ingredients']);
foreach($ingredientsAry as $ingredient){
echo "<li>$ingredient</li>";
}
In fact you can just do a foreach() loop on the explode() value
foreach(explode(',', $row_rs_recipes['ingredients']) as $ingredient){
echo "<li>$ingredient</li>";
}
The explode method already return an array, so you don't have to transform your variable $ingredientsParts into an array.
Just do:
$ingredientsParts = explode(', ', $row_rs_recipes['ingredients']);
foreach ($ingredientsParts as $ingredient)
{
echo "<li>$ingredient</li>";
}
if (!empty($recipe['ingredients'])) {
echo '<ul><li>' . implode('</li><li>', explode(', ', $row_rs_recipes['ingredients'])) . '</li></ul>';
}
You can do this:
$ingredients = explode(',', $row_rs_recipes['ingredients']);
$list = '<ul>';
foreach ($ingredients as $ingredient)
{
$list .= '<li>' . $ingredient . '</li>';
}
$list .= '</ul>';
echo $list;
here is my working php explode code for NON links:
<?php
$textarea = get_custom_field('my_custom_output');
$array = explode(',',$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
$item = trim($item); // clear off white-space
$output .= '<li>' . $item . '</li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
..and the code which defines "my_custom_output", which I input into my textarea field:
text1,text2,text3,etc
..and the finished product:
text1
text2
text3
etc
So that works.
Now what I want to do is make text1 be a link to mywebsite.com/text1-page-url/
I was able to get this far:
<?php
$textarea = get_custom_field('my_custom_output');
$array = explode(',',$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
$item = trim($item); // clear off white-space
$output .= '<li class="link-class"><a title="' . $item . '" href="http://mywebsite.com/' . $item_links . '">' . $item . '</a></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
Now, I would like $item_links to define just the rest of the url. For example:
I want to put input this into my textarea:
text1:text1-page-url,text2:new-text2-page,text3:different-page-text3
and have the output be this:
text1
text2
..etc (stackoverflow forced me to only have two links in this post because I only have 0 reputation)
another thing I want to do is change commas to new lines. I know the code for a new line is \n but I do not know how to swap it out. That way I can put this:
text1:text1-page-url
text2:new-text2-page
text3:different-page-text3
I hope I made this easy for you to understand. I am almost there, I am just stuck. Please help. Thank you!
Just split the $item inside your loop with explode():
<?php
$separator1 = "\n";
$separator2 = ":";
$textarea = get_custom_field('my_custom_output');
$array = explode($separator1,$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
list($item_text, $item_links) = explode($separator2, trim($item));
$output .= '<li class="link-class"><a title="' . $item_text . '" href="http://mywebsite.com/' . $item_links . '">' . $item_text . '</a></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
And choose your string separators so $item_text, $item_links wouldn't contain them.
After you explode the string you could loop through again and separate the text and link into key/values. Something like...
$array_final = new array();
$array_temp = explode(',', $textarea);
foreach($array_temp as $item) {
list($text, $link) = explode(':', $item);
$array_final[$text] = $link;
}
foreach($array_final as $key => $value) {
echo '<li>'.$key.'</li>';
}
to change comma into new line you can use str_replace like
str_replace(",", "\r\n", $output)
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Removing last comma in PHP?
So I have the following code:
<?php
foreach ($movie->Genres as $genre):
?>
<?=$genre->name?>,
<?php
endforeach;
?>
And this will give me the following: Action, Drama, Crime, but I don't need this last comma separator - so my question is what would be the best way to avoid that comma ?
Ps.
If that matters I have 4 loops like this one on my page - for actors, directors, etc.
Write you A-tags to an array and join the items.
<?php
$items = array();
foreach ($movie->Genres as $genre):
$items[] = '' . $genre->name . '';
endforeach;
echo join(', ', $items);
?>
$temp = array();
foreach($movie->Genres as $genre) {
$temp[] = <<<EOL
{$genre->name}
EOL;
}
echo implode(',', $temp);
The other option is to use string concatenation, then a substring to delete the trailing comma:
$temp = '';
foreach(...) {
$temp .= ...
}
echo rtrim($temp, ',');
$a = array();
foreach ( $movie->Genres as $v ){
$a[] = '' . $v->name . '';
}
$s = implode(',', $a);
var_dump($s);