1

I am having this PHP code:

for ($i=0; $i < $numberOfCategories; $i++) { 

    $relatedProduct = echo $categories[$i];
}

What I want to get is to add the value of the variable $i to the variable $relatedProduct. I mean when $i=1,we should have $relatedProduct1

2
  • Why are you echoing and assigning in the same line? Commented May 9, 2016 at 23:28
  • And assigning numbers to variables isn't good practise, why can't you simply leave it as the array? Commented May 9, 2016 at 23:29

1 Answer 1

3

You need variable variables, i.e.:

$categories = array("Sun", "Moon", "Jupiter");
for ($i=0; $i < count($categories); $i++) { 
     ${"relatedProduct" . $i} = $categories[$i];
}

Note:
To assign a variable you simply need = not echo :

$relatedProduct = echo $categories[$i];

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.