SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Enthusiast
    Join Date
    Mar 2006
    Posts
    37
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Array value switch

    I have an array like this:
    Code:
    Array ( [g] => 230 [b] => 205 )
    I want to switch the values so that the result will be:
    Code:
    Array ( [g] => 205 [b] => 230 )
    Of course, I want to do it "smartly", so I have spent the last couple hours on the array function page on PHP.net. All I have so far is this:
    Code:
    $new_array = array_reverse(array_values($original_array));
    Which produces this:
    Code:
    // Original Array
    Array ( [g] => 230 [b] => 205 )
    // New Array
    Array ( [0] => 205 [1] => 230 )
    Am I close?
    Last edited by davidbjames; Oct 27, 2006 at 11:36.

  2. #2
    SitePoint Enthusiast
    Join Date
    Mar 2006
    Posts
    37
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Anyone want to give this a shot?

  3. #3
    SitePoint Wizard silver trophy
    Join Date
    Mar 2006
    Posts
    6,132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    will this array always have 2 elements?

  4. #4
    Sell crazy someplace else markl999's Avatar
    Join Date
    Aug 2003
    Location
    Manchester, UK
    Posts
    4,007
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    And are you using PHP4 or 5?

  5. #5
    SitePoint Enthusiast
    Join Date
    Mar 2006
    Posts
    37
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes, this array will always have two elements, and yes, PHP5.

  6. #6
    SitePoint Wizard silver trophy
    Join Date
    Mar 2006
    Posts
    6,132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    function foo($arr) {
        return 
    array_combine(array_reverse(array_keys($arr)), array_values($arr));
    }

    // although this is probably faster.
    function foo($arr) {
        
    $new = array();
        
    reset($arr);
        list (
    $key1$val1) = each($arr);
        list (
    $key2$val2) = each($arr);
        return array(
    $key1 => $val2$key2 => $val1);


  7. #7
    SitePoint Enthusiast
    Join Date
    Mar 2006
    Posts
    37
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks clamcrusher! That looks fine. I'll profile the two methods and see which is faster.

    It would be nice if PHP had an array function that did this -- reversed the values only of the array.


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
  •