array and function

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
nincha
Forum Contributor
Posts: 191
Joined: Fri Mar 28, 2003 12:30 pm
Location: CA, USA

array and function

Post by nincha »

how would u send an array into a function??
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Post by neophyte »

The same way as any variable:

Code: Select all

$var = 1;

function example(&$var){ // the magic is the "&";
  $foo = 2;
  $foobar = $foo+$var;
   return $foobar;
}

$var = example($var);

echo $var; //Should echo 3
For more examples visit the reference manual

http://us4.php.net/references

You can also change a variable to global scope by declaring variables outside of the function global.

Code: Select all

global $var, $var2;
Include that declaration within the function.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Well actually the "&" is only required if you want to pass the array by-reference which jus plain confuses some people :P

Passing an array to a function is just the same as passing anything else ;)
nincha
Forum Contributor
Posts: 191
Joined: Fri Mar 28, 2003 12:30 pm
Location: CA, USA

Post by nincha »

how do i pass an entire array into a function?
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

RTFM, Chapter 17 Functions, Section: Function arguments.
User avatar
harrisonad
Forum Contributor
Posts: 288
Joined: Fri Oct 15, 2004 4:58 am
Location: Philippines
Contact:

Post by harrisonad »

The replies you got were ok. so listen.
To explain elementarily...

Code: Select all

function eatAll($aray){ // or &$aray if you want to edit the array itself
// do whatever you want to the received array
// bite, chew and swallow...
}

$fruits = array('apple','banana','grapes');
eatAll($fruits);
:roll: yeah, that's kid stuff
User avatar
harsha
Forum Contributor
Posts: 103
Joined: Thu Jul 11, 2002 1:35 am
Location: Bengaluru (Bangalore) > Karnataka > India

Post by harsha »

style/syntax wise php look like C or C++ (I am talking about fucntions)
But concept wise php is php no changes :wink:
Post Reply