0

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!

3 Answers 3

1

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 */ }
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, this is the simplest way. Thought there was some dark function to do the job but well, I'll have to do it "properly". Thanks to all!
1

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.

1 Comment

no, the $arg would be NULL and raise a notice since the array you created is named $arr, not $someArray.. :P
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.