Home > Mobile >  Stop cycle when a condition is true php
Stop cycle when a condition is true php

Time:10-13

I have this code which receives as parameter a date in this format: 2021-10-12.

The function looks for that date entered as a parameter that matches another date stored in an array of x positions.

I need a loop that iterates or searches in all the positions of the array and when it finds the date it finishes the search and returns the one it found.

this is what my array looks like: enter image description here

and the data that I want to bring is what is before /

It means: if the date 2021-10-31 stored in $registro_a_array matches $fechaAMostrar21 it will bring me the number 50 and stop iterating.

$getTransitos = function ($datos_transito, $fechaAMostrar21){
               
                $datos_transito_string = strval($datos_transito);
                $registro_a_array = explode(',', $datos_transito_string);
                $size_array2 = count($registro_a_array);
                
                        $y = 0;
                       while ( $y <= $size_array2 ) {

                        $buscando = str_contains($registro_a_array[$y],$fechaAMostrar21);

                        if ($buscando === true) {
                            $tra_cantidad_ex = explode('/',  $registro_a_array[$y]);
                            $tra = $tra_cantidad_ex[0];
                            $transito_cantidad = intval($tra);   
                           
                        }else{
                            $transito_cantidad = 0;
                              
                        }
                        $y  ;

                       }

                    return $transito_cantidad;

                };

This code works fine when it doesn't find the date, but I can't stop it when it finds the date. i need help.

In theory what I want to achieve is that if the date coincides with the date that is stored in my array (in any position) it stops the search and shows the result.

CodePudding user response:

You can probably rewrite the function like this:

$getTransitos = function ($datos_transito, $fechaAMostrar21) {
    $datos_transito_string = strval($datos_transito);
    $registro_a_array = explode(',', $datos_transito_string);

    // Check all elements

    foreach ($registro_a_array as $elemento) {
        // Split element into cantidad, fecha and wtf
        list ($cantidad, $fecha, $alio) = preg_split('#[/@]#', $elemento);
        // Found fecha?
        if ($fecha === $fechaAMostrar21) {
            return intval($cantidad);
        }
        // If dates are ordered, in the array, and we passed the good one, we won't
        // find our date. So just exit the loop.
        // if ($fecha > $fechaAMostrar21) {
        //     break;
        // }
        // The above ALSO assumes that dates were in YMD format,
        // so that lexicographical ordering ("<") is the same as
        // date ordering. With European format dates, this would
        // not be true.
    }
    // if we're here, we didn't find the date.
    return 0;
};

CodePudding user response:

Much simpler. Just grep for the date, explode and check for the first element:

$result = preg_grep("~/$fechaAMostrar21~", explode(",", $datos_transito_string));
return explode("/", reset($result))[0] ?? 0;

CodePudding user response:

You can reduce the list by looking for each marker and accepting the first value's initial integer:

$foo = [
    '50/2021-10-31@2',
    '93/2021-11-14@2',
    '300/2022-02-14@2',
];

$bar = '2021-11-14';

$getTransitos = fn(string $test, array $values): ?int => array_reduce(
    $values,
    fn($found, $value): ?int => $found ?? (
        strpos($value, $test) ? sscanf($value, '%d/')[0] : null
    ),
    null
);

var_dump($getTransitos($bar, $foo)); // int(93)

https://3v4l.org/hrr7F

Other ways of doing the check:

$getTransitos = function(string $test, array $values): ?int {
    foreach ($values as $value) {
        if (strpos($value, $test)) {
            return sscanf($value, '%d/')[0];
        }
    }
    
    return null;
};

https://3v4l.org/uccaO

$getTransitos = fn(string $test, array $values) => sscanf(array_values(array_filter(
    $values,
    fn($value) => strpos($value, $test)
))[0] ?? '', '%d/')[0] ?? null;

https://3v4l.org/fWGOY

  •  Tags:  
  • php
  • Related