1
Personal I am creating a logic for a hidden friend in PHP.
I’m using the code below to accomplish this:
//Definindo nomes para participar do amigo oculto
$nomes=["Matheus","Alice","Claudia","Leo","Emanuel","Joao"];
//Guardo a primeira formação para definir quem irá tirar quem no amigo oculto;
$ori = $nomes;
//Embaralho de forma aleatória os nome mandados. Sempre serão aleatórios
shuffle($nomes);
foreach($nomes as $key => $n) echo str_pad(strtoupper($ori[$key]),"12"," ",STR_PAD_RIGHT) . ' ==> ' . strtoupper($n) . '<br>';
My question is this::
When I use foreach(shuffle($nomes) as $key => $n)
i have an error. Why can’t I put function inside the foreach? How can I practice this?
Can you tell me what the error would be ?
– Pedro Henrique
Invalid argument supplied for foreach(); the Error I could understand. But I didn’t understand why it doesn’t accept. Where I have more information about this foreach?
– user148170
From what I understand of foreach, it takes only array as parameter, already the shuffle returns a boleano, thus being the reason for the presentation of this error, follows a paragraph about the foreach: 'The foreach constructor provides an easy way to iterate over arrays. The foreach works only on arrays and objects, and will emit an error when trying to use it in a variable with a different data type or in an uninitialized variable.'
– Pedro Henrique
It turns out that the function shuffle changes the allocated array in memory. It does not return a new array. The function only returns if it has successfully done so (true) or not (false)
– Andrei Coelho