简体   繁体   中英

PHP variable variable value in echo

I have a variable variable in PHP.

My Code is

$a1 = "phase";

$phase = $phaseData["Body"]["Data"]["Value"];

I use $$a1 and the code works fine but when I use echo or print to view what's going on it displays the wording $phase not the value of $phaseData

How do i get the print or echo to show the value of $phaseData when using $$a1 ?

I use this code to to display

Echo "A1 \t $$a1\n";

Am I missing something here? $phase is never defined. Even $phase is defined, $phaseData is not. I guess you want to do this:

$a1 = "phase";
$phase = "ABCD";

$phase2 = "${$a1}Data";
echo $phase2;
echo "\n";
//or
$phase3 = $$a1. "Data";
echo $phase3;
echo "\n";

Another example:

$a = "AAA";
$b = "BBB";
$c = "CCC";

$array = array ('a', 'b', 'c');

foreach ($array as $item) {
  echo "\nPrint $item:" . $item;
  echo "\nPrint $a:" . ${$item};
}

echo "\n";

output: 
Print a:a    
Print AAA:AAA    
Print b:b    
Print AAA:BBB    
Print c:c    
Print AAA:CCC

If you want to echo the value of $phaseData you'd need to set it first:

<?php
$a1 = "phase";
$phaseData = 'test';
$phase = "$phaseData";
echo $$a1;

Will output test .


If you want your script to output $phaseData you need to change your quotes to single quotes, so $phaseData doesn't get parsed:

<?php
$a1 = "phase";
$phase = '$phaseData';
echo $$a1;

Will output $phaseData .

Echo "A1 \\t ${$a1}\\n"; worked I just needed the brackets

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM