SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Evangelist GeekSupport's Avatar
    Join Date
    May 2002
    Location
    Southern California
    Posts
    408
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    re-index array after unset?

    Is there a built-in that re-indexes an array if one of the elements were removed?

    PHP Code:
    echo '<pre>';
    $array = array('first','second','third','fourth','fith');
    unset (
    $array[1]);
    sort($array);
    print_r($array); 
    gives me the output below. notice how it is out of "order."
    Code:
    Array
    (
        [0] => first
        [1] => fith
        [2] => fourth
        [3] => third
    )
    i know sort() is to sort it by alpha, but would like an output like this instead (re-sort based on index number)
    Code:
    Array
    (
        [0] => first
        [1] => third
        [2] => fourth
        [3] => fith
    )
    [Edit]
    n/m. i think i found it -- ksort()

    [Edit2]
    arg! it didn't re-index the list. ksort() didn't do it

    [Edit3]
    Found it! array_values() will re-index the list.
    PHP Code:
    echo '<pre>';
    $array = array('first','second','third','fourth','fith');
    unset (
    $array[1]);
    $array array_values($array);
    print_r($array); 
    Code:
    Array
    (
        [0] => first
        [1] => third
        [2] => fourth
        [3] => fith
    )
    Last edited by GeekSupport; Jun 12, 2003 at 18:15.

  2. #2
    Hi there! Owen's Avatar
    Join Date
    Jan 2000
    Location
    CA
    Posts
    1,165
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    There's nothing as satisfying as solving your own problem, is there?

    Owen


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
  •