0

i have an associative array with two keys

$miarray = array(
    array('factor' => $textof[1],    'valor' => $i1),
    array('factor' => $textof[2],    'valor' => $i2),
    array('factor' => $textof[3],    'valor' => $i3),
    array('factor' => $textof[4],    'valor' => $i4),
    array('factor' => $textof[5],    'valor' => $i5),
    array('factor' => $textof[6],    'valor' => $i6),
    array('factor' => $textof[7],    'valor' => $i7),
    array('factor' => $textof[8],    'valor' => $i8),
    array('factor' => $textof[9],    'valor' => $i9),
    array('factor' => $textof[10],    'valor' => $i10),
);

the first key has text and the second key has numeric values. i want to order the array by de second key in ascending order and the add each pair to a variable that will be echoed at the end of the php file.

to sort i use the following

array_multisort(array_column($miarray, 'valor'), SORT_ASC, $miarray);

and to access each pair

foreach ($miarray as $optionArray){ 
$pr .="$optionArray[\"factor\"] - $optionArray[\"valor\"]<br>";
}

nevertheless i get error

[20-Nov-2018 17:58:54 UTC] PHP Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in xxxxxxxxxxxxxxxxx

i have seen many examples but all use print to show the resulting array. thanks for helping.

Ingolf Krauss
  • 161
  • 1
  • 2
  • 23

1 Answers1

2

When you are accessing array keys inside double quotes you can leave out the escaped quotes and do it like this:

$pr .= "$optionArray[factor] - $optionArray[valor]<br>";

Alternately you can concat the desired values:

$pr .= $optionArray['factor'] . ' - ' . $optionArray['valor'] . '<br>';

Either one of those should work, but referencing the keys inside of double quotes the way you have it is the reason for your error.

Read more about how php parses variables here: http://php.net/manual/en/language.types.string.php#language.types.string.parsing

  • The code they provided would not have triggered a syntax error. Granted, it wouldn't have worked either, but their error will not be resolved by this change. – miken32 Nov 20 '18 at 18:32
  • @miken32 - of course it would. here's the error: http://codepad.org/i45ZFCtg – But those new buttons though.. Nov 20 '18 at 18:38
  • Hmm, I stand corrected. I assumed since the quotes were escaped it would just treat the value literally, but I guess the parser realizes it's inside an array index and complains. – miken32 Nov 20 '18 at 18:39
  • I tried posting a working codepad but apparently it uses older php where array_column is not a function yet... here's the working version on 3v4l: https://3v4l.org/jCP2D – But those new buttons though.. Nov 20 '18 at 18:42