Get the index value of an array in PHP

后端 未结 12 2035
迷失自我
迷失自我 2020-12-04 23:05

I have an array:

$list = array(\'string1\', \'string2\', \'string3\');

I want to get the index for a given value (i.e. 1 for <

12条回答
  •  忘掉有多难
    2020-12-04 23:38

    Here is a function that will work for numeric or string indices. Pass the array as first parameter, then the index to the element that needs to be moved and finally set the direction to -1 to move the element up and to 1 to move it down. Example: Move(['first'=>'Peter','second'=>'Paul','third'=>'Kate'],'second',-1) will move Paul up and Peter down.

    function Move($a,$element,$direction)
    {
    
    $temp = [];
    $index = 0;
    
    foreach($a as $key=>$value)
    {
        $temp[$index++] = $key;
    }
    
    $index = array_search($element,$temp);
    
    $newpos = $index+$direction;
    
    if(isset($temp[$newpos]))
    {
            $value2 = $temp[$newpos];
            $temp[$newpos]=$element;
            $temp[$index]=$value2;
    }
    else
    {
        # move is not possible
        return $a; # returns the array unchanged
    }   
    
    $final = [];
    
    foreach($temp as $next)
    {
        $final[$next]=$a[$next];
    }
    
    return $final;
    

    }

提交回复
热议问题