How to echo some code inside a while loop? - php

I have been thinking for hours but i still cant get a solution for this
Basically what i want to do is to echo a separator inside a while, it should be something like this
$num = 1;
while($num < 3){
echo 'dog';
//function to stop while
echo 'separator';
//function to continue while
echo 'cat';
$num++;
}
I want to get this output
dog
dog
dog
separator
cat
cat
cat
I dont know if i explained myself well but hope you understand. Thank you very much in advance.
Update: I know i can make this with 2 while functions but is it possible to make it using only one while function?

definitely yes you can with one while ~function. :)
function OnlyOneWhileFunction($echoThis, $howManyTimes){
$i = 1;
while($i <= $howManyTimes){
echo $echoThis."\r\n";
$i++;
}
}
OnlyOneWhileFunction('dog', 3);
echo 'separator';
OnlyOneWhileFunction('cat', 3);

$num = 0;
$dogs = '';
$cats = '';
$seperator = 'seperator';
while($num < 3){
$dogs .= 'dog';
$cats .= 'cat';
$num++;
}
echo $dogs . $seperator . $cats;
Save the output of each of the dogs and cats then combine at end.

Alternate solution:
$items = array_reverse(array("cat","dog"));
$output = array();
while(count($items) > 0)
{
$item = array_pop($items);
$output[] = implode("\n", array_fill(0, 3, $item));
}
echo implode("\nseparator\n", $output);
You can replace \n with <br> for HTML output (or use nl2br).

Try this:
<?php
$num = 0;
while($num < 7){
if($num < 3)
echo 'dog';
elseif($num == 3)
echo 'separator';
elseif($num>3)
echo 'cat';
echo "<br>";
$num++;
}
?>

You would be better off using a C style for loop and a function call for this:
$recho = function($out, $limit) {
for ($x=0; $x<$limit; $x++) {
echo $out . "\n";
}
}
$recho('dog',3);
echo "seperator\n";
$recho('cat',3);
Put this inside a <pre> on a webpage to get your line breaks, or replace the "\n" with <br> tags.

The following code should work:
$num = 0;
while($num <= 6){
if($num < 3) echo 'dog<br/>';
else if($num == 3) echo 'separator<br/>';
else echo 'cat<br/>';
$num++;
}

Here's another approach if you wanted n number of options and assuming each option is iterated over the same number of times. I'd do some cleanup but this is a quick and dirty approach:
<?php
/**
* Loops items with separator every nth time
* #param array list of items
* #param integer number of iterations
* #param string separator text
*/
function loopItemsWithSeparator(array $items, $count, $separator) {
$items = array_reverse($items);
while(!empty($items)) {
$item = array_pop($items);
for($i = 0; $i < $count; $i++) {
echo $item . "\n";
}
if (count($items) > 0) {
echo($separator . "\n");
}
}
}
loopItemsWithSeparator(array('dog', 'cat', 'bird'), 3, 'separator');
?>

Related

Return every other character from string in PHP

Assume I have a string variable:
$str = "abcdefghijklmn";
What is the best way in PHP to write a function to start at the end of the string, and return every other character? The output from the example should be:
nljhfdb
Here is what I have so far:
$str = "abcdefghijklmn";
$pieces = str_split(strrev($str), 1);
$return = null;
for($i = 0; $i < sizeof($pieces); $i++) {
if($i % 2 === 0) {
$return .= $pieces[$i];
}
}
echo $return;
Just try with:
$input = 'abcdefghijklmn';
$output = '';
for ($i = strlen($input) - 1; $i >= 0; $i -= 2) {
$output .= $input[$i];
}
Output:
string 'nljhfdb' (length=7)
You need to split the string using str_split to store it in an array. Now loop through the array and compare the keys to do a modulo operation.
<?php
$str = "abcdefghijklmn";
$nstr="";
foreach(str_split(strrev($str)) as $k=>$v)
{
if($k%2==0){
$nstr.= $v;
}
}
echo $nstr; //"prints" nljhfdb
I'd go for the same as Shankar did, though this is another approach for the loop.
<?php
$str = "abcdefghijklmn";
for($i=0;$i<strlen($str);$i++){
$res .= (($i-1) % 2 == 0 ? $str[$i] : "");
}
print(strrev($res)); // Result: nljhfdb
?>
reverse the string then do something like
foreach($array as $key => $value)
{
if($key%2 != 0) //The key is uneven, skip
continue;
//do your stuff
}
loop forward, append backward
<?php
$res = '';
$str = "abcdefghijklmn";
for ($i = 0; $i < strlen($str); $i++) {
if(($i - 1) % 2 == 0)
$res = $str[$i] . $res;
}
echo $res;
?>
preg_replace('/(.)./', '$1', strrev($str));
Where preg_replace replaces every two characters of the reversed string with the first of the two.
How about something like this:
$str = str_split("abcdefghijklmn");
echo join("",
array_reverse(
array_filter($str, function($var) {
global $str;
return(array_search($var,$str) & 1);
}
)
)
);

How can I print integer in triangle form

I want to print integer in triangle form which look like this
1
121
12321
I tried this but I do not get the actual result
for($i=1;$i<=3;$i++)
{
for($j=3;$j>=$i;$j--)
{
echo " ";
}
for($k=1;$k<=$i;$k++)
{
echo $k;
}
if($i>1)
{
for($m=$i; $m>=1; $m--)
{
echo $m;
}
}
echo "<br>";
}
Output of this code is:
1
1221
123321
Where am I going wrong, please guide me.
Another integer solution:
$n = 9;
print str_pad ("✭",$n," ",STR_PAD_LEFT) . PHP_EOL;
for ($i=0; $i<$n; $i++){
print str_pad ("", $n - $i);
for ($ii=-$i; $ii<=$i; $ii++){
if ($i % 2 != 0 && $ii % 2 == 0)
print "&#" . rand(10025,10059) . ";";
else print $i - abs($ii) + 1;
}
print PHP_EOL;
}
✭
1
1✬1
12321
1❊3✪3✳1
123454321
1✼3✶5❃5❈3✸1
1234567654321
1✾3✯5✿7❉7✫5✷3✶1
12345678987654321
Or if you already have the string, you could do:
$n = 9; $s = "12345678987654321"; $i = 1;
while ($i <= $n)
echo str_pad ("", $n-$i) . substr ($s,0,$i - 1) . substr ($s,-$i++) . PHP_EOL;
Your code should be this:
for($i=1;$i<=3;$i++)
{
for($j=3;$j>$i;$j--)
{
echo " ";
}
for($k=1;$k<$i;$k++) /** removed = sign*/
{
echo $k;
}
if($i>=1) /**added = sign*/
{
for($m=$i; $m>=1; $m--)
{
echo $m;
}
}
echo "<br>";
}
Try this.
Details:
Your loop is not proper as in case of for($k=1;$k<=$i;$k++), this will print the
repeated number when check the condition for less then and again for equals to.
So remove the equals sign.
reason to add the eqaul sign in if($i>=1) is that the first element will not print if there will not be equals as first it will be print by for loop from where removed the equal sign.
Your output will be this:
1
121
12321
For all the x-mas lovers:
$max = 9; # can be 2 .. 9
for($i = 1; $i <= $max; $i++) {
$line = (str_pad('', $max - $i));
for($ii = 1; $ii <= $i; $ii++) {
$line .= $ii;
}
for($ii = $i-1; $ii > 0; $ii--) {
$line .= $ii;
}
echo $line . PHP_EOL;
}
Output:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
Amazing what computers are able to achieve nowadays! Isn't it?
A little late to the party, but here's yet another solution that uses a "for" loop with two initialization variables and a ternary-based incrementer/decrementer. It's an unorthodox use of a "for" loop, but it's still perfectly valid and arguably makes the code more elegant and easier to follow. I chose to add space before and after each semicolon and omit all other space inside the parentheses so it's easier to visualize each of the three pieces of the "for" loop (initialization, condition, increment/decrement):
$count = 9;
echo "<pre>";
for ($i=1; $i<=$count; $i++) {
echo str_pad("",$count-$i," ",STR_PAD_LEFT);
for ( $j=1,$up=true ; $j>0 ; $up?$j++:$j-- ) {
echo $j;
if ($j==$i) {$up = false;}
}
echo "<br>";
}
echo "</pre>";
Output:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321

PHP Loop: Every 4 Iterations Starting From the 2nd

I have an array that can have any number of items inside it, and I need to grab the values from them at a certain pattern.
It's quite hard to explain my exact problem, but here is the kind of pattern I need to grab the values:
No
Yes
No
No
No
Yes
No
No
No
Yes
No
No
I have the following foreach() loop which is similar to what I need:
$count = 1;
foreach($_POST['input_7'] as $val) {
if ($count % 2 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}
However, this will only pick up on the array items that are 'even', not in the kind of pattern that I need exactly.
Is it possible for me to amend my loop to match that what I need?
You can do this much simpler with a for loop where you set the start to 1 (the second value) and add 4 after each iteration:
for ($i = 1; $i < count($_POST['input_7']); $i += 4) {
echo $_POST['input_7'][$i] . '<br />';
}
Example:
<?php
$array = array(
'foo1', 'foo2', 'foo3', 'foo4', 'foo5',
'foo6', 'foo7', 'foo8', 'foo9', 'foo10',
'foo11', 'foo12', 'foo13', 'foo14', 'foo15'
);
for ($i = 1; $i < count($array); $i += 4) {
echo $array[$i] . '<br />';
}
?>
Output:
foo2foo6foo10foo14
DEMO
Try this:
$count = 3;
foreach($_POST['input_7'] as $val) {
if ($count % 4 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}

How to find string length in php with out using strlen()?

How can you find the length of a string in php with out using strlen() ?
I know this is a pretty old issue, but this piece of code worked for me.
$s = 'string';
$i=0;
while ($s[$i] != '') {
$i++;
}
print $i;
$inputstring="abcd";
$tmp = ''; $i = 0;
while (isset($inputstring[$i])){
$tmp .= $inputstring[$i];
$i++;
}
echo $i; //final string count
echo $tmp; // Read string
while - Iterate the string character 1 by 1
$i - gives the final count of string.
isset($inputstring[$i]) - check character exist(null) or not.
I guess there's the mb_strlen() function.
It's not strlen(), but it does the same job (with the added bonus of working with extended character sets).
If you really want to keep away from anything even related to strlen(), I guess you could do something like this:
$length = count(str_split($string));
I'm sure there's plenty of other ways to do it too. The real question is.... uh, why?
Lets be silly
function stupidCheck($string)
{
$count = 0;
for($i=0; $i<66000; $i++)
{
if(#$string[$i] != "")$count++;
else break;
}
return $count;
}
Simply you can use the below code.
<?php
$string="Vasim";
$i=0;
while(isset($string[$i]))
{
$i++;
}
echo $i; // Here $i has length of string and the answer will be for this string is 5.
?>
The answer given by Vaibhav Jain will throw the following notice on the last index.
Notice: Uninitialized string offset
I would like to give an alternative for this:
<?php
$str = 'India';
$i = 0;
while(#$str[$i]) {
$i++;
}
echo 'Length of ' . $str . ' is ' . $i . '.';
mb_strlen — Get string length
$string ='test strlen check';
print 'mb_strlen(): ' . mb_strlen( $string, 'utf8' ) . "\n\n";
synatx: int mb_strlen ( string $str [, string $encoding = mb_internal_encoding() ] )
str - The string being checked for length.
encoding - The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.
In newer PHP versions, you can use null coalescing operator to achieve this.
<?php
$string = 'test';
for($i = 0; ($string[ $i] ?? false) !== false; ++$i);
echo $i;// outputs length of the string.
Online Demo
You could also cheat with something like:
print strtok(substr(serialize($string), 2), ":");
Or this one is quite amusing:
print array_sum(count_chars($string));
function mystrlen($str)
{
$i = 0;
while ($str != '')
{
$str = substr($str, 1);
$i++;
}
return $i;
}
function findStringLength($string) {
$length = 0;
$lastStringChar1 = '1';
$lastStringChar2 = '2';
$string1 = $string . $lastStringChar1;
$string2 = $string . $lastStringChar2;
while ($string1[$length] != $lastStringChar1 || $string2[$length] != $lastStringChar2) {
$length++;
}
return $length;
}
You can use this code for finding string length without using strlen() function.
<?php
function stringlength($withoutstringlength)
{
$n = 0;
while(substr($withoutstringlength, $n, $n+1) != '')//General syntax substr(string,start,length)
{
$n++;
}
echo $n;
}
stringlength("i am a php dev");
?>
Try this:
function length($value){
if(empty($value[1])) return 1;
$n = 0;
while(!empty($value[$n+1])){
$n++;
}
return $n+1;
}
This doesn't use loops but may face the O(n) issue if strrpos uses strlen internally.
function length($str)
{
return strrpos($str.'_', '_', -1);
}
function my_strlen($str)
{
for($i=-1; isset($str[++$i]); );
return $i;
}
echo my_strlen("q");
$str = "Hello World";
$count= 0;
while( isset($str[$count]) && $str[$count] ) {
$count++;
}
echo $count;
OUTPUT:
11
Renverser un charactère sans Function
class StringFunction {
public function strCount($string) {
$cpt=0;
//isset pour cacher l'erreur
// Notice: Uninitialized string offset
while(isset($string[$cpt])) {
$cpt++;
}
return $cpt;
}
public function reverseChar($str) {
//mes indexes
$start = 0;
$end = $this->strCount($str)-1;
//Si $start est inférieur à $end
while ($start < $end) {
//change position du charactère
$temp = $str[$start];
$str[$start] = $str[$end];
$str[$end] = $temp;
$start++;
$end--;
}
return $str;
}
}
$string = "Bonjour";
$a = new StringFunction();
echo $string . "<br>";
echo $a->reverseChar($string);
This code will help you when you don't want to use any inbuilt function of php.
You can test this here also
http://phptester.net/
<?php
$stings="Hello how are you?";
$ctr=0;
while(1){
if(empty($stings[$ctr])){
break;
}
$ctr++;
}
echo $ctr;
<?php
$str = "aabccdab";
$i = 0;
$temp = array();
while(isset($str[$i])){
echo $str[$i];
$count = 0;
if(isset($temp[$str[$i]])){
$temp[$str[$i]] = $temp[$str[$i]]+1;
}else{
$temp[$str[$i]] = 1;
}
$i++;
}
print_r($temp);
?>
It's going to be a heavy work for your server, but a way to handle it.
function($string){
$c=0;
while(true){
if(!empty($string[$c])){
$c=$c+1;
} else {
break; // Prevent errors with return.
}
}
return $c;
}
$str = "STRING";
$i=0; $count = 0;
while((isset($str{$i}) && $str{$i} != "")){
$i++; $count++;
}
print $count;
This can also help -
$s = 'string';
$temp = str_split($s); // Convert a string to an array by each character
// if don't want the spaces
$temp = array_filter($temp); // remove empty values
echo count($temp); // count the number of element in array
Output
6
<?php
$arr = array('vadapalanai','annanager','chennei','salem','coimbatore');
$min = $arr[0];
$max = $arr[0];
foreach($arr as $key => $val){
if (strlen($min) > strlen($val)) {
$min = $val ;
}
if(strlen($max) < strlen($val)){
$max = $val;
}
}
echo "The shortest array length is : " .$min. " ".strlen($min);
echo "<br>";
echo "The longest array length is: " .$max. " ".strlen($max);
?>
$str = 'I am XYZ'
$count = 0;
$i=0;
while (isset($str[$i])) {
$count = $i;
$i++;
}
echo $count;

PHP: Display comma after each element except the last. Using 'for' statement and no 'implode/explode'

I have this simple for loop to echo an array:
for ($i = 0; $i < count($director); $i++) {
echo ''.$director[$i]["name"].'';
}
The problem here is that when more than one element is in the array then I get everything echoed without any space between. I want to separate each element with a comma except the last one.
I can't use implode so I'm looking for another solution
This should work. It's better I think to call count() once rather than on every loop iteration.
$count = count($director);
for ($i = 0; $i < $count; $i++) {
echo ''.$director[$i]["name"].'';
if ($i < ($count - 1)) {
echo ', ';
}
}
If I remember PHP syntax correctly, this might also help:
$str = "";
for ($i = 0; $i < count($director); $i++) {
$str .= ''.$director[$i]["name"].', ';
}
$str = trim($str, ", ");
A better solution is to avoid looping altogether. I've ignored building the links for the sake of clarity. Note that I don't believe the inability to use implode is a condition. I believe it's a simple statement of, "I can't see how to make this work using implode, so I did it this way instead."
$last_entry = array_pop($director);
if(count($director) > 0) {
echo implode(", ", $director) . " and " . $last_entry;
} else {
echo $last_entry;
}
My preferred method:
$links = [];
for ($i = 0; $i < count($director); $i++) {
$links[] = '<a href="person.php?id='.$director[$i]["id"].'">' .
$director[$i]["name"] . '</a>';
}
echo implode(', ', $links);
Or
$output = "";
for ($i = 0; $i < count($director); $i++) {
if ($output) {
$output .= ", ";
}
$output .= '<a href="person.php?id='.$director[$i]["id"].'">' .
$director[$i]["name"].'</a>';
}
echo $output;
for ( $i=0 ; $i < count($arr)-1 ; $i++ )
{
echo ( $arr[$i]."," );
}
echo ( $arr[count($arr)-1] );
$number = count($director);
for ($i = 0; $i < $number; $i++) {
echo ''.$director[$i]["name"].'';
if($i < $number - 1){
echo ', ';
}
}
Oops, I didn't saw the reply by Tom Haigh, we came with practically the same.
How about something like this? You may want to store the result of "count($director)" in a variable outside the loop so that you do not have to waste resources recalculating it each time the loop is run.
for($i=0; $i<count($director);$i++){
echo ''.$director[$i]["name"].'';
if($i!=count($director)-1){echo ',';}
}
Well, foreach contains for :-)
foreach ($director as $key => $person) {
if ($key !== 0) echo ', ';
echo ''.$person['name'].'';
}
// RENAMED $director to $directors
$links = '';
foreach ($directors AS $director) {
$links .= "{$director['name']}";
if (true !== empty($links)) {
$links .= ', ';
}
}
echo $links;
foreach ($strings as $string){
$superstring .= $string . ', ';
}
$echostring = substr_replace($superstring ,"",-2);
echo $echostring;
Here's my 2 lines solution
// Create your Array
$cities = Array("Rome", "Florence", "Venice");
// implode them
$list = trim(implode (", ", $cities)) ;
// remove last comma
$list = substr ( $list,0 ,strlen( $list ) );
//check result
die ($list);
$count =1;
for ($i = 0; $i < count($director); $i++) {
if ($count!=1) {
echo ' , ';
}
echo ''.$director[$i]["name"].'';
$count++;
}

Categories