Mb Abdullah
Mb Abdullah

Reputation: 31

How to get comma separated values and final value using a for loop?

PHP code:

$b = 1;
$ab = 100;

for ($b; $b < $ab; $b++)
{
    $len = strlen($b);
    $c = 0;
    for ($c; $c < $len; $c++)
    {
        $split = str_split($b);

        if ($split[$c] == 5)
        {
            echo $b . ',';
        }
    }
}

It's result is :

 5,15,25,35,45,50,51,52,53,54,55,55,56,57,58,59,65,75,85,95,

But I want remove the final comma and get the last value.

Upvotes: 0

Views: 3230

Answers (7)

mickmackusa
mickmackusa

Reputation: 47934

Every other answer is too inefficient because they are using str_split() in an inner for() loop to build the array.

Echoing your values and concatenating with a comma each time will require you to write a separate condition to handle the commas. This will just make your code messy. Best practice would be to store all of the values in an array, then use implode() to glue them together with commas -- this avoids the unwanted trailing comma. end() is the best way to extract the last value.

Here is a faster way (because it avoids unnecessary loops and function calls) to dynamically build your array, convert it to a csv string, and access the latest element in the array:

Code:

$d="5";                          // must be declared as string for strpos()
$x11=$d*11;                      // set only duplicate occurrence in range
for($x=1; $x<100; ++$x){
    if(strpos($x,$d)!==false){   // if at least one $d is found
        $array[]=$x;
        if($x==$x11){            // if two $d are found in integer
            $array[]=$x;
        }
    }
}
echo implode(',',$array),"<br>Last number: ",end($array);  // display

Output:

5,15,25,35,45,50,51,52,53,54,55,55,56,57,58,59,65,75,85,95
Last number: 95

This method makes 99 iterations, and 99 strpos() calls, and 20 comparisons to achieve the desired result. Compare this to all other codes on this page, which make 99 outer loop iterations, 99 strlen() calls, 189 inner loop iterations, 189 str_split() calls, and 189 comparisons.


*faster still would be to remove the comparison inside of the strpos() block, add the x11 value to the array outside of the loop, then sort the array before displaying. Like this:

Code:

$d="5";                          // must be declared as string for strpos()
$array[]=$d*11;                  // store only duplicate occurrence in range
for($x=1; $x<100; ++$x){
    if(strpos($x,$d)!==false){   // if at least one $d is found
        $array[]=$x;
    }
}
sort($array);
echo implode(',',$array),"<br>Last number: ",end($array);  // display

Here is alternative method that uses functional iteration:

Code:

$d=5;
$array=array_filter(range(1,99),function($v)use($d){return strpos($v,(string)$d)!==false;})+[$d*11];
sort($array);  // zero-index the keys and position the appended value
echo implode(',',$array),"<br>Last number: ",end($array);  // display

Output:

5,15,25,35,45,50,51,52,53,54,55,55,56,57,58,59,65,75,85,95
Last number: 95

Upvotes: 1

Sahil Gulati
Sahil Gulati

Reputation: 15141

Changes done.

1. Defined $result=array();;

2. Stored values in an array $result[]= $b;

3. Imploded an array with , $result= implode(",", $result);

PHP code demo

<?php

$b = 1;
$ab = 100;
$result=array();

for ($b; $b < $ab; $b++)
{
    $len = strlen($b);
    $c = 0;
    for ($c; $c < $len; $c++)
    {
        $split = str_split($b);

        if ($split[$c] == 5)
        {
            $result[]= $b;
        }
    }
}
$lastElement =end($result);//last element
$result=  implode(",", $result);
print_r($result);

Upvotes: 6

handiansom
handiansom

Reputation: 783

You can also user these codes. Tested it and it worked.

$b = 1;
$ab = 100;
$hasValue = false;
for($b; $b < $ab; $b++){
    $hasFive = false;
    $len = strlen($b);
    $c = 0;
    for($c; $c < $len; $c++){
        $split = str_split($b);

        if($split[$c] == 5){
            $hasFive = true; 
        }
    } 

  if (!$hasValue && $hasFive) {
      echo $b;
      $hasValue = true;
   }else if($hasFive){
      echo ','.$b;
   }
}

Upvotes: 0

Alireza
Alireza

Reputation: 161

simply define a last variable:

$b = 1;
$ab = 100;
$last = 0;
for($b; $b < $ab; $b++){
    $len = strlen($b);
    $c = 0;
    for($c; $c < $len; $c++){
        $split = str_split($b);

        if($split[$c] == 5){
           if($last > 0){
               echo ',';
           }
           echo $b; 
           $last = $b;
        }
   }  
}

put the last value every time in $last.

and for coma, it checks if $last > 0 put coma before $b

Upvotes: 0

Mithu CN
Mithu CN

Reputation: 595

There is two way .Either you use all value in a array or explode the string into array 1st way is

$b = 1;
    $ab = 100;
    $arr=[];

    for($b; $b < $ab; $b++){
        $len = strlen($b);
        $c = 0;
        for($c; $c < $len; $c++){
            $split = str_split($b);

            if($split[$c] == 5){
                $arr[]=$b;//push value into the array
            }
       }  
    }
     echo implode(",",$arr);//create string from array
    echo end($arr);// return the last value of a array

2nd way is

$b = 1;
    $ab = 100;
    $str="";

    for($b; $b < $ab; $b++){
        $len = strlen($b);
        $c = 0;
        for($c; $c < $len; $c++){
            $split = str_split($b);

            if($split[$c] == 5){
              $str .=$b .','; //create a string with name str
            }
       }  
    }
    $str=rtrim($str,','); //remove last comma of this string
    echo $str;
    $arr=explode(",",$str);//convert string to array
    echo end($arr);//return the last value of this array 

Upvotes: 1

Kobbe
Kobbe

Reputation: 316

This removes the last coma AND gives you the last value (as a string). You can always change the string back into an integer.

$b = 1;
$ab = 100;
$string = "";

for($b; $b < $ab; $b++){
    $len = strlen($b);
    $c = 0;
    for($c; $c < $len; $c++){
        $split = str_split($b);

        if($split[$c] == 5){
           $string .= $b .','; 
        }
   }  
}

$string = trim($string,",");
$pos = strripos($string,",");
echo substr($string,$pos + 1);

Upvotes: 0

Ralph John Galindo
Ralph John Galindo

Reputation: 1190

Use rtrim then explode to get an array.

 $b = 1;
 $ab = 100;

 for($b; $b < $ab; $b++){
    $len = strlen($b);
    $c = 0;
    for($c; $c < $len; $c++){
       $split = str_split($b);

       if($split[$c] == 5){
          echo $b .','; 
       }
    }  
 }

 $b = rtrim(',',$b);
 $b = explode(',',$b);
 $b = $b[count($b)-1];

Upvotes: 0

Related Questions