Solved Better way to get PHP Array Shorthand

Assembled / ASSEMBLED
April 26, 2012 at 08:11:20
Specs: Win7, E6550, 4GB DDR2
This is the type of code if find my self repeating many times over and over

line 1) $current_default_category=$con->query("select category_name from categories where default_category='yes';")->fetch_row();
line 2) $current_default_category=$current_default_category[0];

In the first line I am fetching an array from the database and storing it as a variable. In the second line I am overriding the same array variable as the first element of that array, just so I don't have an extra unwanted variable.

There has to be some way to compress both these lines into a single line of code, such that I can directly get the first element from the array returned from the database.
Something like:
$first_element=$con->query("select * from table")->fetch_row()[0];

Or some function that can take two parameters, the array and the index, and return the value at that index. For example:
$fourth_element=get_element_at(3, $con->query("select * from table")->fetch_row());

I hope I have been able to explain properly.


See More: Better way to get PHP Array Shorthand

Report •

May 12, 2012 at 03:00:22
✔ Best Answer
In case this helps someone in the future;
$email=array_pop($con->query("select email from users where user_id='$user_id'"));
This help saving an extra variable to store the result and is only useful if the query fetches a single value from the database.
array_unshift() can also be used in place of array_pop();


Report •
Related Solutions

Ask Question