dslreports logo
 
    All Forums Hot Topics Gallery
spc
Search similar:


uniqs
647

Nordy
join:2007-10-20

Nordy

Member

Loop thru an indefinite set of numbers in php

I'm trying to loop tru a set of numbers based on the initial number. I tried, but I can't seem to find a good way to achieve this. The thing goes inside a while loop.
    <?php
    
    $this = 1;
    
    //If 1 then 1,4,7
    //If 2 then 3
    //If 3 then 10
    
    while ( //mySql while loop ) {
    if ( $this == 1 ) {
    call example() //thrice for 1, 4, 7
    }
    }
    
    function example($a) {
    echo $a+10;
    }
    ?>
 

Here, based on what `$this` is, I need to call function example.

So if `$this = 1`, I need to call `example` thrice - `$a` value `1, 4, 7`. If `$this = 2` I need to call it once, value `3`.

What would be a good way to achieve this?

Toad
join:2001-07-22
Bradford, ON

Toad

Member

Are you looking for PHP or MySQL?

Depending on how many cases you have, you could set up an array of loop options.

 
$options = array( 1 => array(1, 4, 7), 2 => array(3), 3 =>array(10));
 
foreach($options[$this] as $value) {
  example($value);
}
 

Nordy
join:2007-10-20

Nordy

Member

I'm lookin for php. The while loop you see in my question contains a mysql record set.

Mospaw
My socks don't match.

join:2001-01-08
New Braunfels, TX

Mospaw

I realize you posted an example, but don't ever use "$this" as a variable name in PHP unless it's referring to an instance of an object within that object. "$this" is reserved in PHP. Even for an example that never runs, it's a very bad idea.

The usual conventions are "$foo", "$bar", and "$baz", but even "$something" is better. I'm not knocking you ro the code, just warning away from bad habits.

I'm not sure I understand what you're trying to do here. The code isn't passing a parameter to example() inside the while loop, so output will always be the same.

"$this" is only compared to one, so it won't run if $this is 4 or 7. Or will it contain another value?

If you need to compare multiple values, I've found the switch statement works nicely and although somewhat verbose, is clear:

switch ($foo) {
    case 1:
    case 4:
    case 7:
        example($foo);
    break;
 
    default:
        // I always put in a default even if it does nothing.
}
 
This would also make expanding to checking other values a lot cleaner, or even putting in another set and calling different code.