-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
  • 94,607
  • 11
  • 117
  • 176
Rene Limon
  • 614
  • 4
  • 16
  • 34

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
  • 41,125
  • 10
  • 61
  • 80