0

I have multiple variables like $soft0 , $soft1 , $soft2 , $soft3 , $soft4 , $soft5 and also like $fo0 , $fo1 , $fo2 , $fo3 , $fo4 , $fo5 but if i want to apply a if condition here then it showing error. Code:

for ($i=0; $i<=29; $i++) { $soft$i = str_replace(" ", "+", $fo$i); // this line showing an error $link_f_u = $html->find('h3', 0); $keyy = $link_f_u->plaintext; if ($soft$i==$keyy){ continue; } else { publish($soft$i); } } 

Any ideas to modify this code?

1
  • 5
    Why aren't you using an array? Commented Jan 3, 2013 at 19:38

3 Answers 3

3

This will fix your error, but I would highly recommend you take a look at arrays: http://php.net/manual/en/language.types.array.php

for($i=0;$i<=29;$i++){ $softVarName = "soft" . $i; $foVarName = "fo" . $i; $$softVarName = str_replace(" ", "+", $$foVarName); $link_f_u = $html->find('h3', 0); $keyy = $link_f_u->plaintext; if ($$softVarName==$keyy){ continue; } else { publish($$softVarName); } } 
Sign up to request clarification or add additional context in comments.

2 Comments

You need double dollars on your references.
Gahh, remembered them in my test code, forgot in my answer. Thank you, fixed.
2

This should fix the issue.

for($i=0;$i<=29;$i++){ ${'soft' . $i} = str_replace(" ", "+", ${'fo' . $i}); // this line showing an error $link_f_u = $html->find('h3', 0); $keyy = $link_f_u->plaintext; if (${'soft' . $i} == $keyy){ continue; } else { publish(${'soft' . $i}); } } 

2 Comments

I'm certain that $soft{$i} will not work. See: $soft1 = "test"; $i = 1; echo $soft{$i}; Will produce the error Undefined variable: soft
Yes, sorry. My mistake. I've updated the answer, now that should work.
2

Option 1 (best option):

change $soft0 ... $soft10 to arrays looking like $soft[0] .. $soft[10]. You can then use count() in your for loop:

for($i=0;$i<=count($soft);$i++){ $soft[$i] = str_replace(" ", "+", $fo[$i]); $link_f_u = $html->find('h3', 0); $keyy = $link_f_u->plaintext; if ($soft[$i]==$keyy){ continue; } else { publish($soft[$i]); } } 

Option 2:

You can also use double dollar sign, however this is messy and can result in errors that are hard to catch.

$soft_name = 'soft'.$i; $fo_name = 'fo'.$i; $$soft_name = str_replace(" ", "+", $$fo_name); 

2 Comments

I'm fairly certain that $soft{$i} will not work. See: $soft1 = "test"; $i = 1; echo $soft{$i}; Will produce the error Undefined variable: soft
@Supericy I saw it in the other answer. Was in the process of testing for myself. It doesn't work. I've removed it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.