I would like to add a blank line at end of the last $member in below code to differentiate between each group. I have tried with below code
foreach($members as $key => $member)
{
$member = trim(preg_replace('/\s\s+/', ' ', $member));
$dev = " $member part of Form; <br>";
echo str_replace("<br>", "\r\n", $dev);
if($key == count($member)-0)
{
$space = "<br>";
echo str_replace("<br>", "\r\n", $space);
}
}
But It adding a blank space after each 2 line. How can I add space only at end of the last string ?
foreach($members as $key => $member)
{
$member = trim(preg_replace('/\s\s+/', ' ', $member));
$dev = " $member part of Form; <br>";
echo str_replace("<br>", "\r\n", $dev);
if($key == count($members)-1) <!--- ** check this line ---->
{
$space = "<br>";
echo str_replace("<br>", "\r\n", $space);
}
}
** You have counted the value of the key ($member) but actually it will be count of the original array ($members). Here $key starts from zero and it will end previous number of total array count.
I don't know your array structure of $members. You may use bellow code
$count = count($members);
$i = 1;
foreach($members as $key => $member)
{
$member = trim(preg_replace('/\s\s+/', ' ', $member));
$dev = " $member part of Form; <br>";
echo str_replace("<br>", "\r\n", $dev);
if($i == $count)
{
$space = "<br>";
echo str_replace("<br>", "\r\n", $space);
}
$i ++;
}
I'm not sure I understand what you're asking. If you want to add a newline after the last item, you can do so after the loop:
foreach ($members as $key => $member) {
# ...
}
echo "\r\n";
If you need it inside the loop, you will need to test for the last key. One way of doing this is by manipulating the array's internal pointer:
# Set internal pointer of array to the last entry:
end($members)
# Get the key of that last entry:
$lastKey = key($members)
foreach ($members as $key => $member) {
# ...
if ($key === $lastKey) {
echo "\r\n";
}
# ...
}
To add a newline "at the end of the last string", just echo it after the loop. But use the constant PHP_EOL instead of "\r\n".
Concatenating PHP_EOL to the end of each line will give you output that displays more or less the same in a browser and at the command line. Echoing one more PHP_EOL after the loop will insert a blank line that's visible from the command line, but not from the browser. If you need a blank line (more whitespace) in the browser, use CSS instead.
Since you seem to know how to replace <br> tags already, I ignored that part of your code. If you really need to replace those tags instead of just making your text more readable from the command line, you can easily do that.
$ cat code/php/test.php
<?php
$members = array(0 => 'Member0', 1 => 'Member1', 2 => 'Member2', 3 => 'Member3');
foreach($members as $key => $member)
{
$member = trim(preg_replace('/\s\s+/', ' ', $member));
echo " $member part of Form; <br>".PHP_EOL;
}
echo PHP_EOL;
?>
$ php code/php/test.php
Member0 part of Form; <br>
Member1 part of Form; <br>
Member2 part of Form; <br>
Member3 part of Form; <br>
$
$numItems = count($members);
$i = 0;
foreach($members as $key=>$member) {
if(++$i === $numItems) {
$space = "<br">;
echo str_replace("<br>", "\r\n", $space);
}
}
Find the last element of an array while using a foreach loop in PHP
Related
I have a set of numbers in a table field in database, the numbers are separated by comma ','.
I am trying to do the following:
Step 1. : SELECT set of numbers from database and explode it to array :
$array = explode(',', $set_of_numbers);
Step 2. : Print each element of the array as list item by using foreach loop :
foreach ($array as $list_item => $set_of_numbers){
echo "<li>";
print_r(array_list_items($set_of_numbers));
echo "</li>";}
Please anybody tell me what is wrong. Thank you.
$numbers = '1,2,3';
$array = explode(',', $numbers);
foreach ($array as $item) {
echo "<li>$item</li>";
}
Assuming your original $set_of_numbers is simply a CSV string, something like 1,2,3,4,..., then your foreach is "mostly" ok. But your variable naming is quite bonkers, and your print-r() call uncesary:
$array = explode(',', $set_of_numbers);
foreach($array as $key => $value) {
echo "<li>$key: $value</li>";
}
Assuming that 1,2,3,4... string, you'd get
<li>0: 1</li>
<li>1: 2</li>
<li>2: 3</li>
etc...
$numbers = "1,2,3";
$array = explode(",", $numbers);
/* count length of array */
$arrlength = count($array);
/* using for while */
$x = 0;
while ($x < $arrlength) {
echo "<li>$array[$x]</li>" . PHP_EOL;
$x++;
}
echo PHP_EOL;
/* using for classic */
for ($x = 0; $x < $arrlength; $x++) {
echo "<li>$array[$x]</li>" . PHP_EOL;
}
echo PHP_EOL;
/* using for each assoc */
foreach ($array as $value) {
echo "<li>$value</li>" . PHP_EOL;
}
echo PHP_EOL;
/* using for each assoc key */
foreach ($array as $key => $value) {
echo "<li>$key => $value</li>" . PHP_EOL;
}
body, html, iframe {
width: 100% ;
height: 100% ;
overflow: hidden ;
}
<iframe src="https://ideone.com/ZqT4Yi" ></iframe>
You actually don't need to explode on the commas. You can just replace each comma with an ending tag followed by an opening tag and then wrap your whole string in an opening and closing tag.
$set_of_numbers = '1,2,3';
echo '<li>' . str_replace(',', '</li><li>', $set_of_numbers) . '</li>';
// outputs: <li>1</li><li>2</li><li>3</li>
No looping is necessary.
Here is answer for your question to get ride of your problem
$Num = '1,2,3,4,5,';
$Array = explode(',',$Num);
foreach ($Array as $Items)
{
echo "<li>&Items</li>"; // This line put put put in the list.
}
This can easily be achieved by the following code snippet:
<?php
$my_numbers = '1,12,3.2,853.3,4545,221';
echo '<ul>';
foreach(explode(',', $my_numbers) AS $my_number){
echo '<li>'.$my_number.'</li>';
}
echo '</ul>';
The above code will output the following HTML:
<ul><li>1</li><li>12</li><li>3.2</li><li>853.3</li><li>4545</li><li>221</li></ul>
Credits: http://dwellupper.io/post/49/understanding-php-explode-function-with-examples
What i'm trying to do is make my output usable for a spreadsheet.
I want each item in the output without array tags or not mashed together but starting with an asterisk and ending with a % sign.
<?php
$file = file_get_contents('aaa.txt'); //get file to string
$row_array = explode("\n",$file); //cut string to rows by new line
$row_array = array_count_values(array_filter($row_array));
foreach ($row_array as $key=>$counts) {
if ($counts==1)
$no_duplicates[] = $key;
}
//do what You want
echo '<pre>';
print_r($no_duplicates);
//write to file. If file don't exist. Create it
file_put_contents('no_duplicates.txt',$no_duplicates);
?>
Maybe this would give you what you want:
$str = "*" . implode("% *", $no_duplicates) . "%";
echo '<pre>';
echo $str;
echo '</pre>';
I have a string variable which contains some text (shown below). The text has line breaks in it as shown. I would like to search the text for a given string, and return the number of matches per line number. For instance, searching for "keyword" would return 1 match on line 3 and 2 matches on line 5.
I have tried using strstr(). It does a good job finding the first match, and giving me the remaining text, so I can do it again and again until there are no matches. Problem is I do not know how to determine which line number the match occurred on.
Hello,
This is some text.
And a keyword.
Some more text.
Another keyword! And another keyword.
Goodby.
Why not split the text on line-feeds and loop, use the index + 1 as a line number:
$txtParts = explode("\n",$txt);
for ($i=0, $length = count($txtParts);$i<$length;$i++)
{
$tmp = strstr($txtParts[$i],'keyword');
if ($tmp)
{
echo 'Line '.($i +1).': '.$tmp;
}
}
Tested, and working. Just a quick tip, since you're looking for matches in a text (sentences, upper- and lower-case etc...) perhaps stristr (case-insensitive) would be better?An example with foreach and stristr:
$txtParts = explode("\n",$txt);
foreach ($txtParts as $number => $line)
{
$tmp = stristr($line,'keyword');
if ($tmp)
{
echo 'Line '.($number + 1).': '.$tmp;
}
}
With this code you can have all data in one array (Linenumber and position numbers)
<?php
$string = "Hello,
This is some text.
And a keyword.
Some more text.
Another keyword! And another keyword.
Goodby.";
$expl = explode("\n", $string);
$linenumber = 1; // first linenumber
$allpos = array();
foreach ($expl as $str) {
$i = 0;
$toFind = "keyword";
$start = 0;
while($pos = strpos($str, $toFind, $start)) {
//echo $toFind. " " . $pos;
$start = $pos+1;
$allpos[$linenumber][$i] = $pos;
$i++;
}
$linenumber++; // linenumber goes one up
}
foreach ($allpos as $linenumber => $position) {
echo "Linenumber: " . $linenumber . "<br/>";
foreach ($position as $pos) {
echo "On position: " .$pos . "<br/>";
}
echo "<br/>";
}
Angelo's answer definitely provides more functionality and is probably the best answer, but the following is simple and seems to work. I will continue to play with all solutions.
function findMatches($text,$phrase)
{
$list=array();
$lines=explode("\n", $text);
foreach($lines AS $line_number=>$line)
{
str_replace($phrase,$phrase,$line,$count);
if($count)
{
$list[]='Found '.$count.' match(s) on line '.($line_number+1);
}
}
return $list;
}
I have an array, which I am using the following code:
foreach ($taglist as $tag=>$size){
echo link_to(
$tag,
"#search-tag?tag=" . strtolower($tag),
array(
"class" => 'tag' . $size,
"title" => "View all articles tagged '" . $tag . "'"
)
);
}
Now, this simply prints a hyperlink
What I'm looking to do, is to add the pipe char ( | ) after every link, apart from the last one.
Could I do this in a loop?
Thanks
$k = 0;
foreach($taglist as $tag=>$size)
{
$k++;
echo link_to($tage, ...);
if ($k != sizeof($taglist)) echo '|';
}
You can use a plain old boolean variable:
$first = true;
foreach($taglist as $tag=>$size){
if ($first) $first = false; else echo '|';
echo link_to($tage, ...);
}
Note that technically, this code outputs a bar before every element except the first, which has the exact same effect as outputting a bar after every element except the last.
Use a temporary array then join elements /
$links = array();
foreach($taglist as $tag=>$size){
$links[] = link_to($tag, ...);
}
echo implode('|', $links);
You can use a CachingIterator
$links = new CachingIterator(new ArrayIterator($tagList));
foreach($links as $tag => $size) {
echo link_to(/* bla */), $links->hasNext() ? '|' : '';
}
For more info on the CachingIterator see my answer at Peek ahead when iterating an array in PHP
I'm parsing out an HTML table and building an array based on the row values. My problem is the associative keys that are returned have a bit of white space at the end of them giving me results like this:
Array ( [Count ] => 6 [Class ] => 30c [Description] => Conformation Model (Combined 30,57) )
So a line like this:
echo $myArray['Count'];
or
echo $myArray['Count '];
Gives me a blank result.
for now I've got a pretty hacky work around going...
foreach($myArray as $row){
$count = 0;
foreach($row as $info){
if($count == 0){
echo 'Count:' . $info;
echo '<br>';
}
if($count == 1){
echo ' Class:' . $info;
echo '<br>';
}
if($count == 2){
echo ' Description:' . $info;
echo '<br>';
}
$count++;
}
}
The function I'm using to parse the table I found here:
function parseTable($html)
{
// Find the table
preg_match("/<table.*?>.*?<\/[\s]*table>/s", $html, $table_html);
// Get title for each row
preg_match_all("/<th.*?>(.*?)<\/[\s]*th>/", $table_html[0], $matches);
$row_headers = $matches[1];
// Iterate each row
preg_match_all("/<tr.*?>(.*?)<\/[\s]*tr>/s", $table_html[0], $matches);
$table = array();
foreach($matches[1] as $row_html)
{
preg_match_all("/<td.*?>(.*?)<\/[\s]*td>/", $row_html, $td_matches);
$row = array();
for($i=0; $i<count($td_matches[1]); $i++)
{
$td = strip_tags(html_entity_decode($td_matches[1][$i]));
$row[$row_headers[$i]] = $td;
}
if(count($row) > 0)
$table[] = $row;
}
return $table;
}
I'm assuming I can eliminate the white space by updating with the correct regex expression, but, of course I avoid regex like the plague. Any ideas? Thanks in advance.
-J
You can use trim to remove leading and trailing whitespace characters:
$row[trim($row_headers[$i])] = $td;
But don’t use regular expressions for parsing the HTML document; use a proper HTML parser like the Simple HTML DOM Parser or the one of DOMDocument instead.
An easy solution would be to change
$row[$row_headers[$i]] = $td;
to:
$row[trim($row_headers[$i])] = $td;