1

I have a PHP array, something like below:

Array(

  [0] => Array
      (
          [name] => month_year
          [value] => 201609
      )

  [1] => Array
      (
          [name] => advance_amount
          [value] => 50%
      )

)

Using this array, I want to create 2 variables like this:

$month_year = '201609'; 
$advance_amount = '50%'; 

Can anybody tell me is this possible in php?

I tried it using two foreach but I don't have any idea how to precced.

foreach ($_POST as $k => $data) {
  //echo "<pre>", print_r($data)."</pre>";
  foreach ($data as $key => $value) {
    echo $key."<br>";
  }
}

4 Answers 4

2

Use variable variables. Your foreach loop should be like this:

foreach ($_POST as $k => $data) {
    $$data['name'] = $data['value'];
}

// display variables
echo $month_year . "<br />";
echo $advance_amount;
Sign up to request clarification or add additional context in comments.

Comments

1

PHP7 style:

$a = [['name' = 'month_year', 'value' => '201609'], ['name' => 'advance_amount', 'value' => '50%']];


foreach ($a as $line) {
    ${$line['name']} = $line['value'];
}

php > echo $month_year; //201609

Have a look at the Variables reference

Caution

Further dereferencing a variable property that is an array has different semantics between PHP 5 and PHP 7. The PHP 7.0 migration guide includes further details on the types of expressions that have changed, and how to place curly braces to avoid ambiguity.

Comments

1

using list it gives you the cleaner way to solve the issue: for example

$data = [
    [
        'name' => 'month_year',
        'value' => 201609
    ],
    [
        'name' => 'advance_amount',
        'value' => '50%'
    ]
];

list($month_year, $advance_amount) = array_map(function($value){
    return $value['value'];
}, $data);

echo sprintf('Month of the year is %s with porcentage %s', $month_year, $advance_amount);

This will have the result you are looking for with a clearer code.

Month of the year is 201609 with porcentage 50%

Comments

0

first create loop and declare var.

  $data = array(array(
            'name' => 'month_year',
            'value' => 201609,
        ), array(
            'name' => 'advance_amount',
            'value' => '50%',
        )
    );

    foreach ($data as $key => $value) {
        ${$value['name']} = $value['value'];
    }


    echo $month_year;
    echo '<br>';
    echo $advance_amount;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.