Simple loop but cannot get desired results


This problem seemed easy but I am unable to find the answer:

I want a simple loop from -5 to +5 in single steps with this result:

  '-5',  '-4',  '-3',  '-2',  '-1',  '0',  '+1' ,  '+2',  '+3',  '+4',  '+5'
  // The results are to be used here:
  //  $base->bg['-5'] ...  $base->bg['0'] ... $base->bg['+5']
  //  unfortunately  $base->bg['+0'] produces an error because it expects $base->bg['0']

The simple loop I generated results in the middle item being ‘+0’ which is not what I want.

My KLUDGE was to have two loops, first, -5 to -1, hard-code the ‘0’ and then another loop from 1 to 5.

Come on guys and girls there must be a simple solution to this problem.


Yes I agree and try to add an explanation. When looking at the code at a later date it is a lot easier to read the explanation than to try and understand the coding logic.

No it is not my class and it does not have to be PHP 4 compatible. I stumbled upon the class and was impressed how it was programmed for passing a single base colour and the background and foreground colours were adjusted for maximum visibility.

Previously I struggled in changing the background colour of a web page. It was not straight-forward to get all the new colour combinations to be visible. It was a tedious and repetetiive task to step through and hard-code the offending barely visible colour combinations. Now all I have to do is to pick a colour combination and the changing the base colours does not affect readability.

I treated the class as a “Black Box” and tried to create the image in the example and encountered the problem '+0’problem.

This morning I introduced a mt_rand(0,65536) colour and it works fine. I have not tested all the colour combinations :slight_smile:

So, does your class have to remain compatible with PHP4?

Do you have to keep the same methods?

Many thanks for your prompt rely. I will try to integrate your supplied code into my site.

I was trying to use a fornext loop and sprintf(…) without success. Your solution does the job admirably although it is a bit involved.

Here is the reference site where the code is required:

This is the result I am trying to achieve.


or some PHP 5.3 love

$result = array_map(function($i)
    return $i > 0 ? '+' . $i : $i;
}, range(-5, 5));

Take a look at [fphp]range/fphp. :wink:

ini_set('display_errors', true);

function prefix($int){
  return 0 < $int ? '+' . $int : $int ;

echo implode(
  ', ',
    range(-5, 5)

  -5, -4, -3, -2, -1, 0, +1, +2, +3, +4, +5

Or… some SPL love.

ini_set('display_errors', true);

class PrefixedIntegerRange extends ArrayIterator
  public function __construct($from, $to, $step = 1){
    parent::__construct(range($from, $to, $step));
  public function current(){
    $int = parent::current();
    return 0 < $int ? '+' . $int : $int ;

foreach(new PrefixedIntegerRange(-5, 5) as $pos){
  echo $pos . "\