PHP, Creating a dynamic variable

Is there any way through which I can declare the dynamic variable in php. for eg, I am using a for loop and the variable name is $message. and I want to add some dynamic data at the end of the variable name. code is below

foreach ($quant as $quantity) {
            $message.$quantity['type'] =  'Listing ID : '.$quantity['product_id'].' With Quantity: '.$quantity['quantity'].'MT, State- '.$quantity['state_name'].' and Coal type-'.$quantity['coal_type'].'br';
        }

so if the $quantity['type'] = 1, then the variable name should be $message1 and so on. currently I am trying to concatenate but it is wrong. Please tell me how it can be corrected. Thanks in advance

Topic variables php Wordpress

Category Web


After doing a little research I found out the solution myself.

following is the code showing how it can be done

foreach ( $quant as $quantity ) {
    $test  = 'message' . $quantity['type'];
    $test .=  'Listing ID : ' . $quantity['product_id'] 
        . ' With Quantity: '  . $quantity['quantity'] 
        . 'MT, State- '       . $quantity['state_name'] 
        . ' and Coal type-'   . $quantity['coal_type'];
}

Now $message1 will print the result.


Your own solution works I guess (double $$) but usually you do it this way:

$quantity['type'] = 1;
${'message' . $quantity['type']} = 'hello';
echo $message1; // hello

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.