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?
Inline Selection of array element on function return?
Moderator: General Moderators
- phazorRise
- Forum Contributor
- Posts: 134
- Joined: Mon Dec 27, 2010 7:58 am
Re: Inline Selection of array element on function return?
Here,Lets also say that I have no control over the output of the function.
Code: Select all
$temp = test_function();
var_dump($temp[3]);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]);
Re: Inline Selection of array element on function return?
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:
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]);