Tuesday, March 15, 2022

[FIXED] Dynamic variable name php 7.4 and value assigment

Issue

I used to create dynamic variable and assign values to them like this

$total{$column} = 0;

and output it like this

echo $total{$column};

But in php 7.4 {} braces have depricated and we have to use [] braces instead. It is fine when we are dealing with array. but while creating dynamic variable name. It returns following error.

Deprecated: Array and string offset access syntax with curly braces is deprecated in .....

short summary is. I want to create dynamic variable name and assign value like this

$totalA = 20;
$totalB = 10;

This method $total{$column} works fine in older php versions. But Unable to get same result in php 7.4.

Is there anyone to guide.

Thanks


Solution

This piece of code will work in the newest version of PHP as well.

$column = 'A';

${"total{$column}"} = 20;

echo ${"total{$column}"}; // 20

echo $totalA; // 20


Answered By - MichalOravec

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.