Jump to content

passing multi-dimensional arrays into functions


heuristic

Recommended Posts

hi!
I am very new to php with a strong C/C++ background. I currently have a C code which i want to port to php. The code involves passing 2-d arrays into functions. Is it possible to do that in php ( I dont want to use associative arrays. i.e I want to use numerical subscripting for the arrays )

The C code is something like this :

[code]
void myFunc( int myArray[2][3] )
{
      for( int i=0; i<2; i++ )
      {
           for( int j=0; j<3; j++ )
                  cout << myArray[i][j] << " ";
           cout << endl;
      }
}
[/code]

This is what i tried to do in php :

[code]
<?php

function printArray( &$ar )
{
    print("printArray");
    print("<hr>");

    for( $i=0; $i<2; $i++ )
    {
        for( $j=0; $j<3; $j++ )
        {
            $v = $ar[$i][$j];
            print("$v ");
        }
        print("<br>");
    }

    print("<hr>");
}

    $myarray[0][0] = 0;
    $myarray[0][1] = 1;
    $myarray[0][2] = 2;
    $myarray[1][0] = 10;
    $myarray[1][1] = 11;
    $myarray[1][2] = 12;

    printArray( $myArray );
    
?>
[/code]

Why doesnt this work?
Variable names are case-sensitive

$my[!--coloro:#FF6666--][span style=\"color:#FF6666\"][!--/coloro--]a[!--colorc--][/span][!--/colorc--]rray[0][0] = 0;

printArray( $my[!--coloro:#FF6666--][span style=\"color:#FF6666\"][!--/coloro--]A[!--colorc--][/span][!--/colorc--]rray );
It passes the array "by reference" .

Instead of passing a copy of the array to the function, it passes a reference to point to the original array. It's more efficient. Any changes you make to the array inside the function will be made to the original array.

Its like

[code]print_array() {
     global $myarray;

     ...
}[/code]
oh okay i get it. actually, now that you mentioned it, i remembered it. I guess I haven't yet made a function that has needed to do that, so i forgot. Every function I've done so far has just used var/array to retrieve info from db or else blend it up and return some new var(s). I knew it looked vaguely familiar. thx.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.