Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access array returned by a function in php

Tags:

arrays

php

I'm using a template engine that inserts code in my site where I want it.

I wrote a function to test for something which is quite easy:

myfunction() { return '($this->data["a"]["b"] ? true : false)'; } 

The problem is, $this->data is private, and I can't access it everywhere, so I have to use getData(); which causes my problem.

$this->getData()['a']['b'] 

does not work, and assigning the value first doesn't either because it will be used directly in an if() block.

Any ideas?

like image 779
enyo Avatar asked Sep 22 '09 10:09

enyo


People also ask

Can I return an array from a function in PHP?

In PHP you can return one and only one value from your user functions, but you are able to make that single value an array, thereby allowing you to return many values.

Can an array be returned from a function?

C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.

Which function returns the number of elements in an array in PHP?

The count() function returns the number of elements in an array.

How is it possible to return a value from a function in PHP?

A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code. You can return more than one value from a function using return array(1,2,3,4).


1 Answers

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.

like image 147
enyo Avatar answered Sep 27 '22 18:09

enyo