skip to Main Content

i want to get before come array string from array like :

i want this type

$array=array('ABC','BCD','DCB','KBC');

// now iwant get BCD using DCB

echo get_beforestring('DCB',$array);

// I want result BCD

I don’t have any solution for this, if you have any please let me tally. I am trying to solve it but am not able to do so. Because I am new to PHP coding, I don’t have an answer to this question, do you have an answer?

2

Answers


  1. The following function will do what you’ve asked for and return false if the needle is not found in the array or has no preceding value:

    <?php
    
    function getPreviousValue($array, $value) {
        $key = array_search($value, $array);
        return ($key === false || !isset($array[$key-1])) ? false : $array[$key-1];
    }
    
    $array=array('ABC','BCD','DCB','KBC');
    
    var_dump(getPreviousValue($array, 'DCB'));
    
    //returns string(3) "BCD"
    

    If you also want it to work on arrays with non numeric indexes you could do:

    <?php
    
    function getPreviousValue($array, $value) {
        $array = array_values($array);
        $key = array_search($value, $array);
        return ($key === false || !isset($array[$key-1])) ? false : $array[$key-1];
    }
    
    $array=array('a'=>'ABC','b'=>'BCD','c'=>'DCB','d'=>'KBC');
    
    var_dump(getPreviousValue($array, 'DCB'));
    
    //also returns string(3) "BCD"
    
    Login or Signup to reply.
  2. Logic

    1. Increment array key & compare the corresponding value with search item (for example ‘DCB’)

    2. If both are matching, decrement array key & then return the corresponding value. STOP

    3. Else if both does not match, go back to step 1

    Implementation

    Check following function that implements above logic inside a do-while loop

    function get_beforestring(string $needle, array $haystack): ?string {
        $key = 0; $penultimate_key = count($haystack)-2;
        if($haystack[$key]!=$needle) {
            do {
                if($haystack[++$key]==$needle)
                return $haystack[--$key];
            } while ($key<=$penultimate_key);
        }
        return null;
    }
    
    $array=array('ABC', 'BCD', 'DCB', 'KBC');
    echo get_beforestring('DCB', $array);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search