1

I have a simple associative array such as:

key1 => array('table' =>'table1',columns=>array(column1,column2 etc))

When I step through this array with a foreach loop, as below, I cannot seem to call the table name value and insert it into a string I intend to use to make a SQL call.

foreach($tables as $table=>$columnsArray){
    echo $columnsArray['table'];
    $sql="DROP TABLE $columnsArray['table']";
}

I'm obviously doing something wrong, but I cannot fathom what.

If I write $tableName=$columnsArray['table']; I can use that value in $tableName within my string without problem.

Please can someone point out what I am doing wrong ?

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
Chris
  • 23
  • 7
  • [Quoted keys only work using the curly brace syntax](https://stackoverflow.com/questions/2596837/curly-braces-in-string-in-php). – Pyromonk May 28 '17 at 12:23
  • Thanks. So what would be the correct format here? – Chris May 28 '17 at 12:41
  • Anthony seems to have already explained it, but it should be `"DROP TABLE {$columnsArray['table']}"`. I have given you a link that shows a number of possible scenarios, because solving a single misunderstanding is not going to help you avoid this problem in the future. The answer to "why" is, unfortunately, "because": this is simply how PHP syntax works. [The manual](http://php.net/manual/en/index.php) has entries for single/double quotes in strings and the curly braces syntax which will help you. I apologise if my initial response was not transparent enough. – Pyromonk May 28 '17 at 13:03
  • Basically, the reason for why curly braces are needed is so that the interpreter can know where exactly the variable reference ends and the string continues. Let me know if that makes more sense. – Pyromonk May 28 '17 at 13:10
  • 1
    Absolutely clear; thank you very much for taking the time to explain it so well, both of you. – Chris May 28 '17 at 13:23

1 Answers1

0
foreach($tables as $table=>$columnsArray){
    $sql="DROP TABLE " .$columnsArray['table'];
}
Anthony
  • 801
  • 10
  • 20
  • Thank you so much, Anthony; can you also explain to me why I cannot substitute the value into the double-quoted string the way I was trying to? – Chris May 28 '17 at 12:39
  • named arrays inside of double quotes don't need the single quotes you can use $sql="DROP TABLE $columnsArray[table]"; or $sql="DROP TABLE {$columnsArray['table']}"; if you want it to be inside your double quotes – Anthony May 28 '17 at 12:56
  • Wonderful; you are the first person to explain that clearly to me; thanks! – Chris May 28 '17 at 12:58