How do call variable value in other variable name in PHP?
PHP

How do call variable value in other variable name in PHP?

Sometimes, we need to call a variable value into some other variable name. How we can achieve it?

Let’s understand with an example:

<?php
for($i=1; $i<=2; $i++){
   ${'count_'.$i} = 'This is count '. $i;   
   echo ${'count_'.$i};
   echo '<br/>';
   
}
// This is count 1
// This is count 2
?>

Other Example:

<?php 
$numbers = [1,2,3,4,5];
foreach($numbers as $number){
	${'swap_number_'.$number} = $number;
}
	echo $swap_number_1 .'<br/>';
    echo $swap_number_2 .'<br/>';
    echo $swap_number_3 .'<br/>';
    echo $swap_number_4 .'<br/>';
    echo $swap_number_5 .'<br/>';
    
// 1
// 2
// 3
// 4
// 5    
?>

Leave a Reply

Your email address will not be published. Required fields are marked *