Problems with multidimensional arrays and a 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
kral_majales
Forum Commoner
Posts: 36
Joined: Wed Nov 24, 2004 2:47 pm
Location: Dorset, UK

Problems with multidimensional arrays and a function

Post by kral_majales »

Hi all,

I've been writing a script that puts some posted variables together, then formats them in a certain way and outputs them to the browser.

This is all pretty simple, and I managed to use a multidimensional array to store the first names and last names of the people inputted. However, to save space, I decided to turn this into a function, and then call the function. However, the values don't want to work with the function, and I'm really confused!

First of all, I create the multidimensional array:

Code: Select all

$names = array(array( $first, $last) );
Then, I use this function to add new values to the array:

Code: Select all

function namearray( $names, $fname, $lname) {

$namesї] = array( $fname, $lname ) ; 

}
but it doesn't work! When I call the function like this:

Code: Select all

namearray($names, $first2, $last2);
The values aren't entered! What am I doing wrong? If I run the contents of the function on their own (as in, not in a function), it works perfectly! How can I get around this?

K
User avatar
protokol
Forum Contributor
Posts: 353
Joined: Fri Jun 21, 2002 7:00 pm
Location: Cleveland, OH
Contact:

Post by protokol »

You need to set the $names parameter as a reference:

Code: Select all

<?php
function namearray( & $names, $fname, $lname) {
?>
kral_majales
Forum Commoner
Posts: 36
Joined: Wed Nov 24, 2004 2:47 pm
Location: Dorset, UK

Post by kral_majales »

brilliant! it works ! :) :)

thanks very much for your help, it has had me stumped for ages!

K
rehfeld
Forum Regular
Posts: 741
Joined: Mon Oct 18, 2004 8:14 pm

Post by rehfeld »

this should help you understand why that needs to be done


http://php.net/manual/en/language.variables.scope.php
Post Reply