Set a random return to a function

Asked

Viewed 101 times

1

I am creating a function that receives a return x from another function and wanted to test the possibilities to avoid errors.

$array = [1,2];
$i = 0;
foreach ($array as $value) {
    $retorno[$i] =  funcao();
    $i++;
}
echo "Conteudo do array: ";
echo var_dump($retorno);
echo "</br>";
function funcao(){
    return 'falhou' || NULL;
}
$valido = false === array_search(false , $retorno, false);
echo "Teste: ";
var_dump($valido);

I want to randomize this return, it can be a string type 'função falhou' or NULL.

Fiddle

2 answers

3


By directly answering your question, it is possible to return a random value.

The following solution reorders the array randomly and returns the first item.

function funcao(){
    $result = array('falhou', NULL);
    shuffle($result);
    return $result[0];
}

Or something simpler, if it’s only 2 values:

function funcao(){
    return rand(0,1) ? 'falhou' : NULL;
}
  • I will vote on your answer because I found more succinct, about 20 mins after posting the question had reached the same conclusion as yours, randomizing the return, I waited for more answers to see if you had something more direct, like return 'falhou' or NULL

2

My answer is based on your code and your question, but I would like to stress that I found the line logic that arrow the variable $valid very confusing.

I basically used the function Rand(int min, int max) to draw numbers and return 'failed' or NULL randomly.

<?php

function funcao()
{
    // sorteia um número $n entre 1 ou 2 aleatoriamente
    $n = rand (1 , 2);

    // se o $n sorteado for igual a 1, retorna 'falhou'
    // se o $n sorteado for igual a 2, retorna NULL
    if($n==1)
    {
        return 'falhou';    
    }
    else
    {
        return NULL;   
    }
}


$array = [1,2];
$i = 0;

foreach ($array as $value) 
{
    $retorno[$i] =  funcao();
    $i++;
}

echo "Conteudo do array: ";
echo var_dump($retorno);
echo "</br>";


// ATENÇÃO: A lógica dessa linha abaixo é muito confusa e acho que vc deveria reescrevê-la para algo mais inteligível.
// A função array_search retorna o q foi procurado, ou false se não achar o que procurou. 
// O terceiro parâmetro com valor false diz para não comparar tipo*
// Testei aqui e:
// $valido será true se ambos os elementos em retorno forem iguais a 'falhou'
// $valido será false em demais casos, isso pq null é considerado um equivalente de false quando não se verifica tipo
// se o terceiro parâmetro estivesse como true:
//    $valido sempre seria true pq array_search sempre iria falhar e retornaria false que é === false e a comparação retorna true.
$valido = false === array_search(false , $retorno, true);

echo "Teste: ";
var_dump($valido);
  • About $valido = false === array_search(false , $retorno, false); http://answall.com/questions/3390/percorrer-um-array-e-verifica-se-algum-element%C3%A9-empty :)

  • The returns of this function funcao() evening ALWAYS 'failed 'if it fails or NULL if it works On that line $valido = false ===........ that I got from another answer here from the stack, which was even the point I wanted to get to with this question, I test only if there is any NULL element inside the array

  • @Filipemoraes, the point I wanted to reach was in the randomization of the return to be able to validate this function, after I elaborated the return function coming as something that would be in real life "randomly" then I saw that it did not meet my need and adapted :D

  • fiddle $valido = !array_search(false , $instArray, false); doesn’t work

  • fiddle2 $valido = false === array_search('falhou' , $retorno, true); works

  • 1

    @Marcelobonifazio you’re right, the function array_search return False or the index, which in that case may be 0, hence the comparison with the false using 3 equal ===, comparing the value and type, since 0 can be interpreted in PHP as false.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.