0

Im trying to create an array from a variable name. I want to get the information from an sql table and hold that information in an array, however I get an error saying "cannot use [] for reading". Why?

<?php
// SQL Selection CurrentProduct Attributes
$sql = "SELECT * FROM $current_product_name";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
${current_product_name ._array[]} = $row; // add the row in to the array
}
${current_product_name ._length} = count({$current_product_name . _array});
?>

1 Answer 1

1

Don't let the trees hide the forest:

$foo = []; // OK (create empty array with the PHP/5.4+ syntax)
$foo[] = 10; // OK (append item to array)
echo $foo[0]; // OK (read one item)
echo $foo[]; // Error (what could it possibly mean?)

The variable variables notation expects strings (either literals or variables):

$current_product_name = 'Jimmy';
${$current_product_name . '_array'}[] = 33;
var_dump($Jimmy_array);
array(1) {
  [0]=>
  int(33)
}

Said that, your approach looks like a terrific way to produce unmaintainable code. Why not an array with a known name?

$products[$current_product_name][] = $row;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! First for the answer and then for the suggestion!

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.