0

I have an array that looks like this:

$data = array (
  "card" => array(
               "id" => $_GET["id"],
               "user" => dynamicFunction($_GET["id"]),
               "Origin" => $data["card"]["user"]
));

I'm getting an error here.

How can I read the value from current array element user without calling dynamicFunction again since that function will execute DB query again. I don't want to overload my SQL server with unnecessary queries.

Thanks in advance!

6
  • @u_mulder : I don't think it's same as Undefined variable. I'm looking for a solution which will help me in reading element from current array. I m not trying to read from an undeclared variable Commented Mar 2, 2018 at 6:51
  • Currently you have syntax error. replace $_GET("id") with $_GET["id"] Commented Mar 2, 2018 at 6:52
  • $var = dynamicFunction($_GET["id"]); Commented Mar 2, 2018 at 6:53
  • Oops! Sorry. Typo. But still my problem remains the same with element origin Commented Mar 2, 2018 at 6:54
  • Update question. How you accessing your array elements. Commented Mar 2, 2018 at 6:55

1 Answer 1

2

Option 1:

$user = dynamicFunction($_GET["id"]);
$data = array (
    "card" => array(
        "id" => $_GET["id"],
        "user" => $user,
        "Origin" => $user,
));

Option 2:

$data = array (
    "card" => array(
        "id" => $_GET["id"],
        "user" => dynamicFunction($_GET["id"]),
));
$data["card"]['Origin'] = $data["card"]['user'];

Option 3:

$data = array (
    "card" => array(
        "id" => $_GET["id"],
        "user" => $user = dynamicFunction($_GET["id"]),
        "Origin" => $user,
));

And no, you cannot access item af array which is not yet initialized.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the answer. Can you please suggest which one is performance optimized?
Optimization is useless here. You won't gain anything. Choose variant that will be understandable when you will read your code 5-6 months later.
Well, I'll go with Option 3 then

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.