php preg_replace not working within foreach loop - php

I have the following structure :
<?php
$i = 0;
foreach ($users as $user) {
$i++;
$string = '<span>The number is $i</span>';
$string = preg_replace('/\<span.*?\/>$/e','',$string);
echo $string;
}
?>
It appends the $string the number of times foreach loop iterate whereas i just want it to display one time as The number is 4 at the end of the loop. preg_replace works if outside of the loop. How can i echo the output one time and delete rest. I need to do it within the loop and not outside it.

This will do it:
$i = 0;
foreach ($users as $user) {
$i++;
if ($i == count($users)) {
$string = '<span>The number is $i</span>';
$string = preg_replace('/\<span.*?\/>$/e','',$string);
echo $string;
}
}
Though, you might want to consider other options for achieving this. You may maintain your $i variable and output it right after the loop, as this is what this does exactly.
Or, you could just echo "<span>The number is ".count($users)."</span>";.
In my answer, I assumed you totally can't change this things, and that your problem is more complicated than this simple preg_replace. If it's not, consider simplifying things.

The solution I think you need here is output buffering:
// Start the output buffer to catch the output from the loop
ob_start();
$i = 0;
foreach ($users as $user) {
$i++;
// Do stuff
}
// Stop the output buffer and get the loop output as a string
$loopOutput = ob_get_clean();
// Output everything in the correct order
echo '<span>The number is '.$i.'</span>'.$loopOutput;

Related

$_POST array sometimes skips numbers and IF statement ends

I can not figure out how to print all $_POST array items (ending in successive numbers) if one or more numbers do not exist. Not sure how to explain this... For example..
$i = 1;
while( isset($options['item_code'.$i]) )
{
echo $options['item_code'.$i];
$i++;
}
This code works fine as long as the numbers continue to exist in order...
item_code, item_code1, item_code2, item_code3, etc...
But once a number is removed, the if statement stops and the rest of the values are not printed. For example...
item_code, item_code1, item_code3, etc...
Will stop at "item_code1" because item_code2 does not exist.
I've tried solutions given to similar questions here on stackoverflow but they either do not work, do the same thing, or create a continuous loop.
I would appreciate any help that someone can give me here.
you are doing it in wrong way. Please update your code like this. replace $i<=4 with number of element you want to trace
$key = end(array_keys($options));
$dataa = explode('item_code',$key);
$count = $dataa[1];
$i = 1;
while( $i <= $count )
{
if(isset($options['item_code'.$i])){
echo $options['item_code'.$i];
}
$i++;
}
I guess it can be done with an array_filter and strpos functions:
<?php
$codes = array_filter($options, function ($key) {
return strpos($key, 'item_code') === 0;
}, ARRAY_FILTER_USE_KEY);
foreach ($codes as $code) {
echo $code . PHP_EOL;
}
Instead of while use foreach like
foreach($options as $option){
echo $value;
}

Track Last of For Loop

I am learning PHP. I am using for loop like below in one of my php function.
$numbers = $data["data"];
for ($i = 0;$i < count($numbers);$i++) {
$w->send($numbers[$i]);
}
I want check that if its last number, I need sleep some second and want call one other function. I do not know how can I do it. can anyone please suggest me what should I do for it?
Thanks
$numbers = $data["data"];
for ($i = 0,$c=count($numbers);$i < $c;$i++) {
$w->send($numbers[$i]);
if($i==$c-1){
sleep(60);
//call your function here;
}
}
You can simply do, what you want to do, after the loop:
$numbers = $data["data"];
foreach ($numbers as $number) {
$w->send($number);
}
$w->send($otherNumber);
sleep($forSomeSeconds);
I also changed the for loop to a foreach loop after the comment made by Elementary.

How to get last iteration of for loop when limit and increment is dynamic?

I have seen some question related to this one like
How to check for last loop when using for loop in php?
Last iteration of enhanced for loop in java
but I am not getting exact solution because in my case increment and end limit both are dynamic.
Requirement:- I do not want comma after last element printed.
$inc=11;
$end=100;
for($i=1;$i<=$end;$i=$i+$inc){
echo $i==$end?$i:"$i,"; // 1,12,23,34,45,56,67,78,89,100
}
In above code I know that last element($i) will be 100($end).
So I can write condition as $i==$end but in below case it won't work.
$inc=12; // Now $inc is 12
$end=100;
for($i=1;$i<=$end;$i=$i+$inc){
echo $i==$end?$i:"$i,"; // 1,13,25,37,49,61,73,85,97,
}
Now last element 97 has comma which I need to remove.
Thanks in advance.
Keep it simple:
$numbers = range(0, $end, $inc);
$string = implode(",", $numbers);
echo $string;
You can see it here: https://3v4l.org/BRpnH
;)
You can just use,
echo $i+$inc>$end?$i:"$i,";
It checks whether this is the last possible iteration instead.
Use rtrim to remove the last comma
$inc = 12; // Now $inc is 12
$end = 100;
$print = '';
for($i=1;$i<=$end;$i=$i+$inc){
$print .= ($i==$end)? $i : "$i,"; // 1,13,25,37,49,61,73,85,97,
}
$print = rtrim($print, ',');
echo $print;
You can do it in this way :
<?php
$inc=4;
$end=10;
for($i=1;$i<=$end;$i=$i+$inc){
echo ($i+$inc-1)>=$end?$i:"$i,"; // 1,5,9
}
?>
This code is working on prime number case also not given you result like // 1,13,25,37,49,61,73,85,97, always gives you result like // 1,13,25,37,49,61,73,85,97 no comma added after any prime number.

for() loop fails to stop looping ?

I'm trying to print an array until it's empty.
Here is my code:
for ($i=0; $array[0][$i]!=NULL; ++$i){
echo $array[0][$i];
}
However it looks like it performs the echo one extra time, I don't know why ?
Here's my output for an array that contains data up to array[0][2].
I am sure that array[0][3] is empty, I tried it with if(array[0][3]==NULL)
Test 0
Test 1
Test 2
( ! ) Notice: Undefined offset: 3 in C:\... on line 9
Any idea ?
You should use the arrays length when you loop... Or try this instead:
foreach($array[0] as $val) {
echo $val;
}
It makes perfect sense, really. PHP can not magically know that the next id (in your example, index number '3') is not set, it has to access the variable to determine that. That's also why you get the notice.
In short, it does not execute the body of the for loop, but it has to execute the test to determine whether or not to continue.
Anyway, use a foreach loop, or calculate the number of items in the array first and increment $i till they match.
Possible alternatives to you code that should actually work.
foreach($array[0] as $val)
if($val===null)
break;
else
echo $val;
or
$arrlen=count($array[0]);
for($i=0;$i<$arrlen;$i++)
if($array[0][$i]===null)
break;
else
echo $array[0][$i];
or even
$i=0;
while($array[0][$i]!==null) { //not recommended, can cause infinite loop
echo $array[0][$i];
$i++;
}
The reason why it's throwing an error is because an array index that does not exist is not equal to NULL. You can modify your code to this:
for ($i=0; isset($array[0][$i]); ++$i){
echo $array[0][$i];
}
Or try this instead:
$ctr = count($array[0]);
for ($i = 0; $i < $ctr; $i++) {
echo $array[0][$i];
}
The loop should finish after reaching the end of the array.

Print a letter before each row without using <ol> or a compiled array

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";
}

Categories