1

What I want to do is use a FOR loop to fetch and display the value of strings already submitted from a form.

I've tried the following code (produced to give you some idea of what I'm trying to achieve) but it doesn't work. I've also tried various manuals but they seem to be concerned with incrementally processing the VALUE of strings and not the strings themselves.

I've searched Google and various forums. I've also checked my PHP primer but it doesn't contain the answer.

    $clip1="A";
    $clip2="B";
    $clip3="C";
    $clip4="D";
    $clip5="E";
    $clip6="F";
    $clip7="G";
    $clip8="H";
    $clip9="I";
    $clip10="J";

    for ($t=1; $t<=10; $t++)

    {echo "$clip[$t]";}

I was EXPECTING the above code to fetch the value of each string in turn. What I was EXPECTING was something like this;

ABCDEFGHIJ

I get no errors. My code just produces nothing at all. What am I doing wrong?!

Thank you so, so much in advance.

1
  • Turn on error reporting! Your variables $clip1, $clip2...$clip10 are type string - then in your loop you reference an undefined array type variable $clip[]... that won't work - your error reporting should tell you you have an undefined variable $clip[]... Commented Oct 7, 2019 at 21:57

2 Answers 2

1

It looks like you might be trying to use PHP's variable variables, in which case you need to change your syntax a bit:

$var = "clip$t"
echo $$var;

Things would be a lot cleaner if you used an array instead:

$clips = [
  'A', 'B', 'C', 'D', 'E', 'F',
  'G', 'H', 'I', 'J',
];

foreach ($clips as $clip) {
  echo $clip;
}

// Or...

for ($t = 0; $t < count($clips); $t++) {
    echo $clip[$t];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you both! Why didn't I think of that?! I think the issue was I wasn't sure what to CALL what I was trying to do and therefore found myself stumbling down some confusing paths. You've solved it. Thank you so much.
0
$clip1="A";
$clip2="B";
$clip3="C";
$clip4="D";
$clip5="E";
$clip6="F";
$clip7="G";
$clip8="H";
$clip9="I";
$clip10="J";

for($t=1; $t<=10; $t++){
    echo $clip.$t."<br />";
}

Of course, like @Unimportant said, you might be better off storing these in an array:

//fill the array
$clip = [];
foreach(range("A", "J" as $char){
   clip[] = $char;
}

//print the array
foreach($clip as $char){
    echo $char."<br />";
}

1 Comment

Thank you all. I’ve solved it now. Couldn’t have done it without you.

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.