Access an Array Returned by a Function

Access array returned by a function in php

Since PHP 5.4 it's possible to do exactly that:

getSomeArray()[2]

Reference: https://secure.php.net/manual/en/language.types.array.php#example-62

On PHP 5.3 or earlier, you'll need to use a temporary variable.

Return array in a function

In this case, your array variable arr can actually also be treated as a pointer to the beginning of your array's block in memory, by an implicit conversion. This syntax that you're using:

int fillarr(int arr[])

Is kind of just syntactic sugar. You could really replace it with this and it would still work:

int fillarr(int* arr)

So in the same sense, what you want to return from your function is actually a pointer to the first element in the array:

int* fillarr(int arr[])

And you'll still be able to use it just like you would a normal array:

int main()
{
int y[10];
int *a = fillarr(y);
cout << a[0] << endl;
}

How to use an array that was returned from a method in Java

just store the returned array in a local one

public static void main(String[]args){
int[][]array = fillArray("fileName"); // call the method
// traverse the array using a loop

for(int i=0;i<array.length;i++)
for(int j=0;j<array[i].length;j++)
System.out.println(a[i][j]); // do something with elements

}

How do I access data in an array that was returned by a function?

Forget whatever it is you think you want to learn about "neat tricks".

  1. Don't declare a variable just to reassign it to something else of a completely different type on the next line. This is code smell, and in languages like TypeScript it's a big no-no because it breaks type-safety also makes it harder for the engine to optimize.
  2. If you're having a hard time reading a statement, it's because it needs to be broken up into simpler statements, not condensed into a smaller, harder-to-read statement.

With that in mind, consider the following:

const reference = await this.getReference(DocStore, AdData, 'budget')
const budgets = reference[0].data

This has no ambiguity, and it clearly conveys what is being done, step-by-step. You await the reference, then get the data from the first entry in the reference array. In addition, having a const declaration is nice since you can immediately conclude that the values will never be re-assigned as you're reading the code.

This is also good for optimization, because using a constant reference can reduce the amount of calls to unboxing its value in the underlying engine since it will remain the same type and same reference for the duration of its lifetime.



Related Topics



Leave a reply



Submit