Passing array as a function parameter

Asked

Viewed 9,803 times

5

I want to receive the array containing numbers 3, 15 and 23 and array output display double. Only it is giving the following error:

Warning: Missing argument 1 for criando_array(), called in

<?php

function criando_array($array){

            $array = array();

            return $array;
    }

    function dobrar_array(){

        $dobrar = criando_array();

        foreach($dobrar as $lista){

            echo $lista*2 . "<br>";
        }

    }

    $resposta =  dobrar_array(array(3, 15, 23));

    echo $resposta;


?>

3 answers

9


The code has some problems, it can be much simpler than this:

<?php
function dobrar_array($dobrar) { //agora está recebendo um parâmetro aqui
    //a função que era chamada aqui não era necessária e não fazia nada útil
    foreach($dobrar as $lista){
        echo $lista*2 . "<br>";
    }
}
$resposta = dobrar_array(array(3, 15, 23));
echo $resposta;
?>

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thank you. It worked correctly.

6

The function criando_array() it doesn’t make much sense what it does is to receive a parameter with values, then that same variable($array) receives an empty array that is returned at the end of the function.

The error is here in the syntax, criando_array need a login that is mandatory as shows your signature:

function criando_array($array){

Look how the call is being made:

 function dobrar_array(){
    $dobrar = criando_array(); // deveria ser algo como $dobrar = criando_array($variavel);

I suggest that in function dobrar_array set a parameter to do the multiplication directly and can also discard the function criando_array

function dobrar_array($array){
    foreach($array as $lista){
        echo $lista * 2 ."<br>";
    }
}

 dobrar_array(array(3, 15, 23)); 
 // ou ainda
 $array = array(3, 15, 23);
 dobrar_array($array);
  • Your comment helped me. Thanks Dude.

3

To use an array as a parameter, simply do the following in the function:

function dobrar_array($parametro=array()){

        foreach($parametro as $lista){

            echo $lista*2 . "<br>";
        }

    }

    $resposta =  dobrar_array(array(3, 15, 23));

    echo $resposta;
  • 1

    Thanks for the reply. Gave a lightening here.

Browser other questions tagged

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