0

I have an array $array_file_names that contains 50 elements which are the names of the text files I wish to create. But the name of the file The code I have written is written below:

for($i=0;$i<$total_file_count;$i++)
{
    $file="$array_file_names[$i].txt";
    file_put_contents($file, "Testing....");
}

But the files that is created has the name $array_file_names[$i] and not the one that is contained in the array.

1 Answer 1

1

This will work:

for($i=0;$i<$total_file_count;$i++)
{
  $file=$array_file_names[$i].".txt";
  file_put_contents($file, "Testing....");
}

Using variables inside double quoted strings is tricky sometimes, specially with arrays, and lead to strange bugs. I prefer the old fashioned concatenation.

And a cleaner way to writing this is using foreach:

foreach($array_file_names as $file_name)
{
  file_put_contents($file_name.".txt", "Testing....");
}
Sign up to request clarification or add additional context in comments.

3 Comments

I have tried both the codes but the files are now not getting created.
@NamanArora, then do a print_r($array_file_name); and show us the result.
@NamanArora, glad to help! If the answer helped you, could you please mark it as correct? Thanks!

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.