Rearrange array in php

Discussion in 'PHP' started by greatlogix, Mar 31, 2010.

  1. #1
    I have dynamic array like this

    $color[0] = 'Red'
    $color[1] = 'Green'
    $color[2] = 'Blue'
    $color[3] = 'black'
    $color[4] = 'white'

    I want to move "black" to first index of the array and move "Red" to down at index 2. How can i do this? Any code snippet or article?
     
    greatlogix, Mar 31, 2010 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    jestep, Mar 31, 2010 IP
  3. Narrator

    Narrator Active Member

    Messages:
    392
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    80
    #3
    This should work
    
    	  function moveToFirst(&$array, $str)
    	  {
    		  	$key=array_search($str,$array);
    			if($key) unset($array[$key]);
    			array_unshift($array,$str);  
    			return $array;
    	  }
    
    PHP:
    I also tried a function that reorders the whole array with a foreach but this one was a lot faster.
     
    Narrator, Mar 31, 2010 IP