Page 1 of 1

Inline Selection of array element on function return?

Posted: Tue Aug 16, 2011 3:24 pm
by Dorin85
Hi folks,

I'm wondering if there is a way to reference a single element of an array which a function returns.

Lets say I have a function named test_function() it takes no arguments and returns an array. Lets also say that I have no control over the output of the function.

In order to dump a specific element of that array I would do this:
$temp = test_function();
var_dump($temp[3]);

I'm looking to replace those two lines with something like this...
var_dump(test_function()[3]);

Yet that approach doesn't work.

Any suggestions?

Re: Inline Selection of array element on function return?

Posted: Wed Aug 17, 2011 10:19 am
by phazorRise
Lets also say that I have no control over the output of the function.
Here,

Code: Select all

$temp = test_function();
var_dump($temp[3]);
as you said, you don't have control over output so the returned array might be empty, with only 1 element, 2 elements or so....

While with above code, you are dumping the contents of array on index position 3.
What if, the returned array doesn't have 3 elements? An error will occur saying Undefined offset:3.

This is example, at least you must know the offsets of array. So you can use-

Code: Select all

$temp = test_function();
$index=rand(0,count($temp));// will give you random index between 0 to max index.
var_dump($temp[$index]);
Perhaps, post that function that generate array. And other's might give you some advice.

Re: Inline Selection of array element on function return?

Posted: Wed Aug 17, 2011 10:39 am
by Dorin85
The question really was just about directly accessing an array element of an arbitrary function. It's safe to assume that the function will always return populated arrays.

Essentially what I'm doing is:

Code: Select all

$date_start = array($request->getParam('month_start'), $request->getParam('year_start'));
$date_start_conv = date_parse($date_start[0]); //this is where I'd like the inline change to take place.  This isn't a huge deal, I've just come across this same scenario quite a few times and I thought I'd look into a more elegant solution.
$numeric_days_in_month = cal_days_in_month(CAL_GREGORIAN, $date_start_conv['month'], $date_start[1]);