SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    Community Advisor silver trophybronze trophy
    dresden_phoenix's Avatar
    Join Date
    Jun 2008
    Location
    Madison, WI
    Posts
    2,801
    Mentioned
    34 Post(s)
    Tagged
    2 Thread(s)

    range() question

    if suppose I could do this with a "for" loop, but I am wondering if there is a more graceful alternative. I want to create array of a containing a range of DIFFERENT numbers; for the sake of this example lets say 1-10, when i use "range(1,10)" it creates an array with the desired range but it starts with the key "0"


    example:
    $variable[0]=1;
    $variable[1]=2;
    ...
    $variable[9]=10;

    is there a way to do this, (without using a "for" loop) where I can chose what key the range starts?

    example:
    $variable[x]=1;
    $variable[x+1]=2;
    ...
    $variable[X+9]=10;

  2. #2
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    $Start 10;
    $Range array_fill(0$Startnull);
    $Range array_merge($RangeRange(110));
    $Range array_filter($Range);
    var_dump($Range); 
    or, condensed:
    PHP Code:
    $Start 10;
    $Range array_filter(array_merge(array_fill(0$Startnull), Range(110))); 
    Edit:

    Now removes NULL values - so you have an array starting from the value you wanted rather than an array starting from 0 and full of NULLs before the values.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  3. #3
    SitePoint Addict
    Join Date
    Aug 2005
    Posts
    207
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Just subtract - 1 in your starting range and use array slice...

    PHP Code:
    <?php

    $start 
    1;

    $end 10;

    $out array_slice range $start 1$end ), $start$endtrue );

    print_r $out );

    ?>

  4. #4
    @php.net Salathe's Avatar
    Join Date
    Dec 2004
    Location
    Edinburgh
    Posts
    1,397
    Mentioned
    63 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    array_combine(range(514), range(110)) 
    Salathe
    Software Developer and PHP Manual Author.

  5. #5
    Community Advisor silver trophybronze trophy
    dresden_phoenix's Avatar
    Join Date
    Jun 2008
    Location
    Madison, WI
    Posts
    2,801
    Mentioned
    34 Post(s)
    Tagged
    2 Thread(s)
    wow.. and I that thought there was no way of doing this ....lol. THANK YOU all.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •