-2

I have the following code:

<?php
    $atributos = array("id","attr1","attr2","attr4");
    function dinamico()
    {
       $stringData = implode(",",$atributos);
       echo $stringData;
    } 
?>

and it give this:

Warning: implode(): Invalid arguments passed

if I declare this array inside function, It works but not out of it.

Note: I need to declare it outside because I use this array too times.

Karoly Horvath
  • 91,854
  • 11
  • 113
  • 173
Rene Limon
  • 594
  • 4
  • 15
  • 31

1 Answers1

1

To avoid using global, you can pass the array as an argument to your function.

<?php

function dinamico($atributos)  // add a parameter here
{
   $stringData = implode(",",$atributos);
   echo $stringData;
}

$atributos = array("id","attr1","attr2","attr4");  // declare the array outside the function

dinamico($atributos);  // pass the array to the function when you call it

An advantage to doing it this way rather than using global $atributos; inside your function (which would also work) is that it allows your function to be self-contained rather than forcing it to depend on the existence of a variable with a certain name outside its scope.

Don't Panic
  • 39,820
  • 10
  • 58
  • 75