开发者

Get array keys when in argument in PHP

开发者 https://www.devze.com 2023-01-27 17:43 出处:网络
I\'m passing some arrays as arguments inside a function. For example: test($someArray[2][3])开发者_运维知识库;

I'm passing some arrays as arguments inside a function. For example:

test($someArray[2][3])开发者_运维知识库;

In that case the function gets the value stored in (2,3) but there is a way to get the keys value (2,3) from inside the function to work with? The function should use the x,y position of the value to do some calculations.

Thanks!


Not this way, no. If you call test($someArray[2][3]), then PHP will only pass the value, but not any reference where this value comes from. Its cleaner to pass the values separately anyway

function test($x, $y, $value) { /* do something */ }


Nope, the subscript will be performed before the function receives it.

So if your code is...

$someArray = array(
   2 => array(3 => 'Hello');
);

function test($arg) {

}

test($someArray[2][3]);

Then $arg will be a string Hello. It doesn't know or care about where it came from.


You're only passing the single element at [2][3]; once inside the function, there is no array. If you need the positions, you should pass the array/element and the indices separately:

test($someArray, 2, 3); // if you might access other elements too

or:

test($someArray[2][3], 2, 3); // if you don't need other elements
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号