Skip to content
PHP Logo

In PHP, how can a random element be selected from an array of file names and manipulated before writing it to a file?

To select a random element from an array of file names in PHP and manipulate it before writing it to a file, you can use the `array_rand()` function to get a random key from the array, then use that key to access the random file name. You can then manipulate the file name as needed before writing it to a file.

php
<?php
// Array of file names
$fileNames = ['file1.txt', 'file2.txt', 'file3.txt'];

// Get a random key from the array
$randomKey = array_rand($fileNames);

// Get the random file name
$randomFileName = $fileNames[$randomKey];

// Manipulate the file name as needed
$manipulatedFileName = strtoupper($randomFileName);

// Write the manipulated file name to a file
file_put_contents('output.txt', $manipulatedFileName);
?>