Jump to content

Theory question based on empty arrays


j.smith1981

Recommended Posts

I am just interested when you see something like this:

 

<?php
$myarray = array();
?>

 

When delcaring an empty array, this is when you don't know what data will be held inside that array right?

 

I mean if say you where making a playlist in PHP, which is what I am working on at this very moment in time, you wanted to list all the files (MP3 files if you will) as an array so you'd have say all 25 mp3 files in a restricted directory, but you don't know yet what the file names will be.

 

To make the loop work to fill up the array this is when you would use the tiny little snippet above yes? Sorry please correct me if I am wrong this is the whole point of this thread!

 

Also what would happen if you did the loop but not do the above snippet before the loop?

 

Thank you and I look forward to any replies,

Jeremy.

Link to comment
https://forums.phpfreaks.com/topic/244591-theory-question-based-on-empty-arrays/
Share on other sites

I thought so just wanted to clarify why you'd use that outside of a loop.

 

All the very tiny snippet of code would do is read down a given directory shown within the opendir() function.

 

Then list them in a drop down box and include those (which are style sheets in this case I am working on) to show different arrangements of colours and even positioning on boxes should the user change which style sheet they want to see the page in.

 

In a sense a version of true web development, changing content or layout presentation in this case using PHP.

 

No real point in this but just having some fun with PHP.

  Quote

<?php
$dir = new DirectoryIterator('C:\\MP3');

foreach ($dir as $fileinfo) {
    if ($fileinfo->isFile()){
        $mp3s[] = $fileinfo->getFilename();
    }
}

print_r($mp3s);

 

Do I really need to?

 

And what happens when there aren't any files? $mp3s is then undefined as compared to being empty.

 

I typically initialize an empty array before using it, out of habit instead of creating it via the square bracket syntax. But like thehippy pointed out, you do not need to initialize using array();

Technically in case like that you might not get an error, but that doesn't mean it's a good idea. Not only is it a bad idea for the reason KingPhilip pointed out, but what about when you come and look at the code later? If it's more complex than that basic example it might not be entirely clear where $mp3s is coming from and you'll be confusing yourself.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.