0

Can we copy all the dynamic values to array for eg: I have a function like this

<?php

 $list_a = array(); //defining an array
 $list_b = array();
 $list_c = array();
addText($a,$b,$c)
{
 $list_a[] = $a;
 $list_b[] = $b;
 $list_c[] = $c;
}

I will pass different values to addText() function after that I have to access those inserted value using foreach from another function.

How can we do that .

prabhu
  • 301
  • 2
  • 3
  • 10

4 Answers4

3

Just define your php variable as global.

Eg. global $list_a,$list_b,$list_c;

When you are using that variable in any function then first declare above variables in that function. Eg:

addText($a,$b,$c)
{
global $list_a,$list_b,$list_c;
 $list_a[] = $a;
 $list_b[] = $b;
 $list_c[] = $c;
}
Domain
  • 11,562
  • 3
  • 23
  • 44
2

To accomplish this you have to use concept of global variable

Try this:

$list_a = array(); //defining an array
 $list_b = array();
 $list_c = array();
function addText($a,$b,$c)
{
 global $list_a, $list_b, $list_c;
 array_push($list_a,$a);
 array_push($list_b,$b);
 array_push($list_c,$c);
}
addText('12','23',12);
echo '<pre>';
print_r($list_a);
print_r($list_b);
print_r($list_c);
PHP Worm...
  • 4,109
  • 1
  • 25
  • 48
0

This would work but it is bad design. See here why.

<?php

$list_a = array(); //defining an array
$list_b = array();
$list_c = array();
function addText($a,$b,$c)
{
    global $list_a, $list_b, $list_c;

    $list_a[] = $a;
    $list_b[] = $b;
    $list_c[] = $c;
}
function foreachThem()
{
    global $list_a, $list_b, $list_c;

    foreach($list_a as $item)
    {
         //...
    }
    foreach($list_b as $item)
    {
         //...
    }
    foreach($list_c as $item)
    {
         //...
    }
}

A better way would be saving them in a parent array (this is optional but it reduces the amount of parameters and therefor the amount of code) and passing it as reference. See here for info on passing by reference.

<?php

$theLists = array(
    "a" => array(),
    "b" => array(),
    "c" => array()
);
               // note the '&'
function addText(&$lists, $a,$b,$c)
{
    $lists["a"][] = $a;
    $lists["b"][] = $b;
    $lists["c"][] = $c;
}
                   // '&' is not needed here
function foreachThem($lists)
{
    foreach($lists["a"] as $item)
    {
         //...
    }
    foreach($lists["b"] as $item)
    {
         //...
    }
    foreach($lists["c"] as $item)
    {
         //...
    }
}
Community
  • 1
  • 1
Ch33f
  • 609
  • 8
  • 17
0

Try this,

<?php

 $list_a = array(); //defining an array
 $list_b = array();
 $list_c = array();
addText($a,$b,$c)
{
   $list_a[] = $a;
   $list_b[] = $b;
   $list_c[] = $c;
}
public function 'function_name'($list_a, $list_b, $list_c) {
  foreach ($list_a as $list) {
    echo $list;
  }
}
Vignesh Bala
  • 889
  • 6
  • 25