Array passing as a parameter of a function

5

I want to get the array containing the numbers 3, 15 and 23 and with an output array display twice. But it is giving the following error:

  Warning: Missing argument 1 for creating_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;


?>
    
asked by anonymous 04.03.2015 / 02:56

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;
?>

See working on ideone .

    
04.03.2015 / 03:05
6

The function% criando_array() not make much sense what it does is receive parâmentro with values after the same variable ( $array ) recebece an empty array that is returned at the end of the function.

The error here is the syntax% criando_array need one entry that is required as shown in your signature:

function criando_array($array){

Look at how the call is being made:

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

I suggest that the function% dobrar_array set a parameter to directly to the multiplication and can also dispose of 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);
    
04.03.2015 / 03:05
3

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

function dobrar_array($parametro=array()){

        foreach($parametro as $lista){

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

    }

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

    echo $resposta;
    
04.03.2015 / 03:13