Home » Php » php – Index of array looks like function name

php – Index of array looks like function name

Posted by: admin February 25, 2020 Leave a comment

Questions:

I learning about laravel and php and recently I have encountered some problem which I try to describe:
I’m trying to echo an average age of male. I’m using this function which I found on forum related to laravel:
$resultMale = DB::select($maleSQL, array(1));

My problem is that it returns arrays which indexes are taken from this query

$maleSQL = "SELECT books.name, books.book_date, AVG(reviews.age) FROM books, reviews where name='{$this->name}' and sex='m' and {$this->condition};";

and so if I want to access to data which is indexed as “name” I use:

echo "{$resultMale[0]->name}";

But my problem starts when i try to access data under AVG(reviews.age)

 echo "{$resultMale[0]->AVG(reviews.age)}";

It is detected as a function inside this array not as an index.
error in laravel

I’ve tried using foreach loop as well as:

 $bypassFunctionAVG="avg(reviews.age)";
 echo "{$resultMale[0]->{$bypassFunctionAVG}}";

I’ve tried also renaming this index without success.
So there goes my question: how do I echo data of this array under this index?

How to&Answers:

This might work…

$avg = $resultMale[0]->{"AVG(reviews.age)"}
echo $avg;

Otherwise, try using an alias (notice, “AS avg”)

$maleSQL = "SELECT books.name, books.book_date, AVG(reviews.age) AS avg FROM books, reviews where name='{$this->name}' and sex='m' and {$this->condition};";

echo $resultMale[0]->avg;

Also double quotes is not necessary to echo variables as you have done it above. They are useful in some cases but not necessary. echo $var, echo “$var”, echo “{$var}” will all do the same thing.

These things will have the same result…

$value = 25;
echo "The value is $value.";
echo "The value is {$value}.";
echo "The value is " . $value . ".";
echo 'The value is ' . $value . '.';

These will not have the same result as above…

// use {} around non-trivial variable expressions
echo "The value is $object->value.";

// single quotes don't do anything to variables
echo 'The value is $value.';