ImAZ
ImAZ

Reputation: 59

display series of characters in a string using loops in php

I want to make a series, e.g, 1/2 + 3/4 + 5/6 + 7/8 + 9/10 + 11/12 as a string using loops in php. write now i have written this code:

$output='';
    for ($i=0; $i < 6; $i++) 
    { 
        $output=$output.($i+1+$i).'/'.($i+2+$i);
        if ($i==5) 
        {
            break;
        }
        else
        {
            $output=$output.'+';
        }
    }
    echo nl2br("\n4: $output");

output:

1/2 + 3/4 + 5/6 + 7/8 + 9/10 + 11/12

is there any other better approach to do that?

Upvotes: 0

Views: 385

Answers (4)

dale landry
dale landry

Reputation: 8600

as a string using loops in php. --> display as a string...

Use for loop and modulus operator %. Display first key, a forward slash, then continue the iteration outside that conditional and display the next key, then display a plus sign.

Continue iteration until you evaluate if the value is at the end of the array. Two conditionals inside the loop.

I used a iterator defined as $i as using a foreach loop would start at zero and you would have to do some extra code to get the last value.

$myArray = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16); 

$stmt = NULL;
  for($i = 0; $i < count($myArray); $i++){
    if($myArray[$i] % 2 ){
      $stmt .= $myArray[$i]."/"; 
    }else{
      if($myArray[$i] !== end($myArray)){
        $stmt .= $myArray[$i].' + ';
      }else{
        $stmt .= $myArray[$i];
      }
    }
  }

OUTPUT:

enter image description here

Upvotes: 1

Ωmega
Ωmega

Reputation: 43673

preg_replace('/(\d+) \+ (\d+)/', '$1/$2', implode(" + ", range(1, 12)));

https://www.ideone.com/dKUIwc

Upvotes: 2

Justinas
Justinas

Reputation: 43481

Start loop from 1 and make step of 2 instead of one. Then put every sequence to array and finally implode it with +

$output = [];

for ($i = 1; $i <= 12; $i += 2) {
    $output[] = $i . '/' . ($i + 1); 
}

echo implode(' + ', $output);

Upvotes: 1

u_mulder
u_mulder

Reputation: 54841

With minimum of code it is:

$output = [];
for ($i = 0; $i < 6; $i++) { 
    $output[] = (2 * $i + 1) . '/' . (2 * $i + 2);
}
echo implode(' + ', $output);

Upvotes: 1

Related Questions