I'm making a website with wordpress for my company and i have a question for you
I have an url like this
http://mysuperwebsite/?_sft_category=cx+ms+lol
And i would like to grab the argument of this, so i tried
$motsclefs = $_GET['_sft_category'] ;
and a basic echo
echo'<div>'.$motsclefs.'</div>';
This is cool but now this return me something like this in a single div
cx ms lol
My desire is to cut those words, to have as much div as my words
To be more specific i would like to have something like this
<div class="1">cx</div>
<div class="2">ms</div>
<div class="3">lol</div>
So, i understood that i have to consider those "+" in the url to separate my words ?
Thanks ;)
You can try this.
$tempArr=explode(' ',$motsclefs);
for($i=0;$i < count($tempArr);$i++)
{
echo '<div>'.$tempArr[$i].'</div>';
}
As mentioned by Jon Stirling use explode and foreach.
<?php
$motsclefs = 'cx ms lol';
$divs = '';
foreach(explode(' ', $motsclefs) as $key => $element) {
$divs .= sprintf ('<div class="%s">%s</div>' . PHP_EOL, $key + 1, $element);
}
You can split the string by a space, if $motsclefs is a string with spaces separating the arguments, which is how it looks from your question:
$arguments = explode(" ", $motsclefs);
Then iterate through them:
foreach ($arguments as $argument) {
echo "<div>$argument</div>";
}
For different classes;
$i = 1;
foreach ($arguments as $argument) {
echo "<div class='class$i'>$argument</div>";
$i++;
}
$i increases for each loop round which will give you a new number with every iteration.
Related
How can I prevent the insertion of a comma at the end of the title3?
foreach ($_POST['titles'] AS $title) {
echo "{$title},";
};
Result:
title1,title2,title3,
Update :
It comes as a form data, this is array. Don't come this way; title1,title2,title3,
<form>
<select name="titles[]">
<option>title1</title>
<option>title2</title>
<option>title3</title>
<option>title4</title>
</select>
</form>
just use implode() - which is the equivalent to .join():
echo implode(',', $_POST['titles']);
or simply:
echo implode($_POST['titles']);
if you really want to use a loop - an index is required in order to determine the last one element. a foreach loop does not provide any index to compare to; that's why a for loop is rather suitable:
// $titles = explode(',', $_POST['titles']);
$titles = $_POST['titles'];
for($i=0; $i < sizeof($titles); $i++) {
echo $titles[$i];
if($i+1 != sizeof($titles)){echo ',';}
}
looks like you could skip the foreach altogether and just do this:
echo implode(',',$_POST['titles']);
You should use implode instead.
$string = implode(',', $_POST['titles']);
I agree with the other answers - implode() is the way to go. But if you'd rather not/keep on the path you're on...
$output = "";
foreach ($_POST['titles'] AS $title) {
$output .= "{$title},";
};
echo substr($output, 0, -1);
The code below is a simple version of what I am trying to do. The code will read in two files, see if there is a matching entry and, if there is, display the difference in the numbers for that item. But it isn't working. The first echo displays the word but the second echo is never reached. Would someone please explain what I am missing?
$mainArry = array('Albert,8');
$arry = array('Albert,12');
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
if (in_array($kword[0], $mainArry)) {
echo 'line '.$line. ' has count of '.$kword[1] . '<br>';
}
}
Your $mainArry contains a single element: the string 'Albert,8'. It looks like you want to use it as an array (elements 'Albert' and '8') instead of a string.
You mention the code will read from two files, so you can 'explode' it to a real array, as you do with $arry. A simpler approach would be using str_getcsv() to parse the CSV string into $mainArry.
$inputString = 'Albert,8';
$mainArry = str_getcsv($inputString); // now $mainArry is ['Albert','8']
$arry = array('Albert,12');
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
if (in_array($kword[0], $mainArry)) {
echo 'line '.$line. ' has count of '.$kword[1] . '<br>';
}
}
Test it here.
You are attempting to compare the string Albert with Albert,8, so they won't match. If you want to check if the string contains the keyword, assuming your array has more than one element, you could use:
$mainArry = array('Albert,8');
$arry = array('Albert,12');
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
foreach ($mainArry as $comp) {
if (strstr($comp, $kword[0])) {
echo 'line '.$line. ' has count of '.$kword[1] . '<br>';
}
}
}
example: https://eval.in/728566
I don't recommend your way of working, but this is a solution, basically the process you apply to the $arry should also apply to the $mainArry you're trying to compare it to.
$mainArry = array('Albert,8');
$arry = array('Albert,12');
/***
NEW function below takes the valus out of the main array.
and sets them in their own array so they can be properly compared.
***/
foreach ($mainArry as $arrr){
$ma = explode(",",$arrr);
$names[] = $ma[0];
$values[] = $ma[1];
}
unset($arrr,$ma);
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
/// note var reference here is updated.
if (in_array($kword[0], $names)) {
echo '<br>line '.$kword[0]. ' has count of '.$kword[1] . '<br>';
}
}
Yeah, MarcM's answer above does the same thing in a neat single line, but I wanted to illustrate a little more under the hood operations of the value setting. :-/
I am using the following PHP snippet to echo data to an HTML page.
This works fine so far and returns results like the following example:
value1, value2, value3, value4, value5,
How can I prevent it from also adding a comma at the end of the string while keeping the commas between the single values ?
My PHP:
<?php foreach ($files->tags->fileTag as $tag) { echo $tag . ", "; } ?>
Many thanks in advance for any help with this, Tim.
If
$files->tags->fileTag
is an array, then you can use
$str = implode(', ', $files->tags->fileTag);
implode(", ", $files->tags->fileTag);
A simple way to do this is keep a counter and check for every record the index compared with the total item tags.
<?php
$total = count($files->tags->fileTag);
foreach ($files->tags->fileTag as $index => $tag) {
if($index != $total - 1){
echo $tag.',';
} else{
echo $tag;
}
?>
<?php
echo implode(",",$files->tag->fileTag);
?>
Assuming you're using an array to iterate through, how about instead of using a foreach loop, you use a regular for loop and put an if statement at the end to check if it's reached the length of the loop and echo $tag on it's own?
Pseudocode off the top of my head:
for($i = 0, $i < $files.length, $i++){
if ($i < $files.length){
echo $tag . ", ";
} else {
echo $tag;
}
}
Hope that helps x
Edit: The implode answers defo seem better than this, I'd probably go for those x
HTML template
<b><!--{NAME}--></b>
...
..
..
<b><!--{ADDRESS}--></b>
PHP Array
array('name'=>'my full name', ..... , 'address'=>'some address ');
I have lots of template files and have to parse each of them and replace it the str_replace given data in associative arrays.
I need your suggestions to improve this process or any other technique/tool that might be helpful
Edit: Current version of code
static function ParseTemplate($data,$template){
$html=$read==true ? self::GetCached($template,true) : $template ;
foreach($data as $key=>$value){
if(is_array($value) ){
foreach($data[$key] as $aval)
$html = str_replace("<!--{".$key."}-->",$aval,$html);
}
else $html = str_replace("<!--{".$key."}-->",$value,$html);
}
return $html;
}
thanks
Why not using a template engine such as Mustache, here for the PHP version
if the array keys are always the same as the template word inside the braces, do something like this:
foreach ($array as $key => $value) {
$html = str_replace("<!--{$key}-->", $value, $html)
}
if performance is important, it may be better to use strpos on the html, and go over the placeholders one by one. it will be quicker that doing str_replace many times on a large string. but if performance is not an issue, it's not necessary.
EDIT:
$index = strpos($html, "<!--");
while ( $index !== false ) {
// get the position of the end of the placeholder
$closing_index = strpos($html, "}-->", $index);
// extract the placeholder, which is the key in the array
$key = substr ($html, $index + 5, $closing_index);
// slice the html. the substr up to the placeholder + the value in the array
// + the substr after
$html = substr ($html, 0, $index) . $array[$key] .
substr ($html, $closing_index + 4);
$index = strpos($html, "<!--", $index + 1);
}
NOTE: this wasn't tested, so there may be some inaccuracies with the indexes... it's just to give you a general idea.
I think this is more efficient then str_replace, but you know what? this can use some benchmarking...
If I understand the question correctly, I think the following should work fine unless I'm missing something.
$a = array('name'=>'my full name','address'=>'some address');
foreach($a as $k=>$v)
{
$html = str_replace('<!--{'.strtoupper($k).'}-->',$v,$html);
}
Witch is the best way to print a letter (beginning from A) before each row of a list without using html ordered list <ol><li></li>...</ol> and without using an array that contain the alphabet?
es:
A. first row
B. second row
C. third row
thanks for your suggestion!
How about this, using ++ on a variable containing a letter...
$letter = 'A';
foreach ($list as $item) {
echo $letter++, '. ', $item, "\n";
}
See the increment operator's manual page for more information on this behaviour. Essentially, calling ++ on a one-character string, where that character is an A-Za-z letter, will make the string into the next letter.
You could use a string and substr it on every iteration:
<?php
$alph = 'abcdefghijklmnopqrstuvwxyz';
$rows = array(); //whatever your rows are that you're printing
$i = 0;
foreach($rows AS $r): ?>
<?php echo substr($alph, $i, 1); ?> x row<br>
<?php $i ++; endforeach; ?>
Something like this?
<?php
for($i=0; $i<10; $i++)
{
echo chr(65+$i) . '. ' . $1;
}
?>
$l = 'a';
foreach($rows as $row) {
echo strtoupper($l).". {$row}\n";
$l++
}
Depending upon how long your list is, you can get away with this:
$start = 'A';
foreach ($lists as $li) {
echo "$start. $li\n";
$start++;
}
If you don't even want to specify the start, you can use the ascii codes too.
foreach ($lists as $num => $li) {
echo chr($num + 65) . ". $li\n";
}