#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2000
    Posts
    3
    Rep Power
    0
    I am convinced there is an easy way to do this but I have an array and need an easy way to swap two elements of it.

    For example:
    $myArray = array ("one", "two", "three", "four", "five");
    [swap elements two and three]

    $myArray is now array("one", "three", "two", "four", "five");

    I am a bit ashamed to be asking this but I could really use your help if there is an easy way to do it. Thanks!


    kp
  2. #2
  3. No Profile Picture
    Apprentice Deity
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    Jul 1999
    Location
    Niagara Falls (On the wrong side of the gorge)
    Posts
    3,237
    Rep Power
    19
    function swap (&$ary,$element1,$element2)
    {
    $temp=$ary[$element1];
    $ary[$element1]=$ary[$element2];
    $ary[$element2]=$temp;
    }

    To use this in your example you would do this:

    swap($myArray,2,3);

    The order of the element arguments, obviously, is irrelevent. And of course this can be used with assoc. arrays. e.g.:

    swap($myArray,'index','other_index');

    If you do this often use the function.

Similar Threads

  1. Printing related elements from a multi-dimensional array
    By lisamar1 in forum Perl Programming
    Replies: 3
    Last Post: February 16th, 2004, 10:11 AM
  2. Replies: 2
    Last Post: January 28th, 2004, 12:06 AM
  3. sort: find duplicate string elements in array
    By sciencelife in forum Java Help
    Replies: 3
    Last Post: January 27th, 2004, 01:29 PM
  4. array read using STDIN
    By rashmihn in forum Perl Programming
    Replies: 3
    Last Post: December 30th, 2003, 11:25 AM
  5. Replies: 1
    Last Post: December 10th, 2003, 09:51 AM

IMN logo majestic logo threadwatch logo seochat tools logo