0

If I println($values) I will get the results of the correct attributes for each file fully written as shown in array as key on left but I would like to run the results against the array (valuesCodes) to get the values on right.

Any help would be greatly appreciated, I'm brand new to PHP.

$valuesCodes = array(
"Anfield" => "ANF",
"Lower" => "LOW",
"Burntown"=>"BUR");


foreach ($Files as $file) {
    $contents = simplexml_load_file($file);
    $values = $contents->Match->attributes()->stadium;
}
  • 1
    Show one example of $values. If $values would contain "Anfield" you could `$echo $valuesCodes[$values] ?? 'N/A';` and it will output `ANF`. – Markus Zeller Aug 27 '22 at 14:37
  • If I was to println($values) I would get the following Anfield Lower Burntown. I would then like to return the value(shortened version ANF etc from array valuesCodes) for each of the results(i.e Anfield Burntown Lower) – GuinnessGorilla Aug 27 '22 at 15:03
  • I have tried echo $valuesCodes[$values] but get nothing back. – GuinnessGorilla Aug 27 '22 at 15:09
  • You need to put the $valuesCodes array on top **before** the foreach loop. – Markus Zeller Aug 27 '22 at 15:11
  • Apologies my code has the $valueCodes array before the foreach loop; I've edited the question to reflect this. It doesn't return the value nonetheless, I'm pretty stumped. – GuinnessGorilla Aug 27 '22 at 15:16
  • Then the keys don't match. Try trimming whitespaces and linebreaks. `$echo $valuesCodes[trim($values)] ?? 'N/A';` Did you put it at the end inside of the foreach loop? – Markus Zeller Aug 27 '22 at 15:19
  • Thanks a mill Markus!! trim solved it. I'm very grateful for your help. Something useful for me to remember going forward! – GuinnessGorilla Aug 27 '22 at 15:27

1 Answers1

0

For best practice I renamed some variables (Look for PSR).

First of all the $valueCodes should be on top, else they are not known inside the foreach.

As it looked like your stadium value contain whitespaces or line breaks which can be eliminated by trimming them.

$valueCodes = [
    "Anfield"  => "ANF",
    "Lower"    => "LOW",
    "Burntown" => "BUR",
];

foreach ($files as $file) {
    $contents = simplexml_load_file($file);
    $value    = trim($contents->Match->attributes()->stadium);
    echo $valueCodes[$value] ?? 'N/A';
}
Markus Zeller
  • 8,516
  • 2
  • 29
  • 35