Home > front end >  How to initialize array in PHP with a variable value
How to initialize array in PHP with a variable value

Time:10-18

I'm running into a issue with PHP array. Basically I want to sort a 2D array by its value. If I initialize literal array value and sort it works fine. But the literal array value is created at run time and assigned to a variable that is further assigned to array which is suppose to sort but it is not sorting with variable assigned value to array. In other languages I have worked we use & symbol before a variable to get its literal value, not sure what I use in PHP.

Here is the example that works fine and it is sorting by age

$age = array("Giselle"=>"25", "Amara"=>"15", "Josephine"=>"28", "Penelope"=>"18" ); 
asort($age); 

Here is the same example with variable assigned to array which doesn't sort

$custprof = '"Giselle"=>"25", "Amara"=>"15", "Josephine"=>"28", "Penelope"=>"18"';
$age = array($custprof); 
asort($age); 

Would appreciate any help.

CodePudding user response:

To avoid security risks you can use explode function like below.

$custprof = '"Giselle"=>"25", "Amara"=>"15", "Josephine"=>"28", "Penelope"=>"18"';
$custprof = explode('", "', $custprof);

$age = [];
foreach( $custprof as $single_custprof )
{
  $array     = explode('"=>"', $single_custprof);
  $key       = str_replace('"', "", $array[0]);
  $value     = str_replace('"', "", $array[1]);

  $age[$key] = $value;
}

asort( $age );

CodePudding user response:

Try this.

$custprof = '"Giselle"=>"25", "Amara"=>"15", "Josephine"=>"28", "Penelope"=>"18"';
eval( '$age = array(' . $custprof . ');' ); 
asort( $age ); 
  • Related