Scan dir, create php array with new keys starting from 1 and rising with each file found (all my keys are [1])
Get the solution ↓↓↓Trying to scan a directory then put the files it finds into an array which I can then later call in a for each loop but not getting the results I desire with my current code...
<?php
$files = scandir('audio');
foreach ($files as $file) {
$arr = array($file);
$iOne = array_combine(range(1, count($arr)), array_values($arr));
echo "<pre>";
print_r($iOne);
echo "</pre>";
}
?>
produces..
Array
(
[1] => .
)
Array
(
[1] => ..
)
Array
(
[1] => audio1.mp3
)
Array
(
[1] => audio2.mp3
)
Array
(
[1] => audio3.mp3
)
Array
(
[1] => audio4.mp3
)
When I wanted
Array
(
[1] => audio1.mp3
[2] => audio2.mp3
[3] => audio3.mp3
[4] => audio4.mp3
)
Note I also removed.
&..
from the second output.
I'm very new to PHP and arrays and as such despite me reading several similar questions it is my lack of understanding that is stopping me achieve my desired results. Thanks in advance.
EDIT: I've tried the answer suggested by Nick
<?php
$files = scandir('audio');
$files = array_slice($files, 2);
$files = array_combine(range(1, count($files)), $files);
foreach ($files as $file) {
echo "<pre>";
print_r($file);
echo "</pre>";
}
?>
but this displays..
audio1.mp3
audio2.mp3
audio3.mp3
audio4.mp3
not
Array
(
[1] => audio1.mp3
[2] => audio2.mp3
[3] => audio3.mp3
[4] => audio4.mp3
)
Answer
Solution:
$files
is already an array; all you need to do is remove the.
and..
entries from it. They will be the first two entries assuming your filenames all start with letters. Then you can re-index if you want to:
$files = scandir('audio');
$files = array_slice($files, 2);
$files = array_combine(range(1, count($files)), $files);
echo "<pre>";
print_r($files);
echo "</pre>";
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: xml parsing error: no root element found
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.