Array declarations

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dacer
Forum Newbie
Posts: 5
Joined: Wed Mar 21, 2012 6:08 am

Array declarations

Post by dacer »

Hi, I used to use asp/aspx/vb code, so I'm confused with php.

I want to create an array, but I don't know how many elements it will have. I can do:

Code: Select all

$myArray = array();
And then populate it with

Code: Select all

$myArray[index] = 'value';
This work fine, but I have this warning on server side (apache error log)

PHP Notice: Undefined offset: 0 in ..

How can I declare myArray as array, and later set so many elements as I need. For example in Vb, "redim array(5)".

Thanks
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Array declarations

Post by requinix »

There's something else going wrong with your code. It's not with the array - you've got the right idea.
Here's one thing I see: you don't have quotes around the "index" in that second bit of code. If that's supposed to be a string then it needs quotes.

What's your actual code? You may simply have a typo, or maybe you're misunderstanding (or not even aware) of some other PHP thing.
dacer
Forum Newbie
Posts: 5
Joined: Wed Mar 21, 2012 6:08 am

Re: Array declarations

Post by dacer »

sorry, i want to say:

Code: Select all

$myArray[$index] = 'value';
or

Code: Select all

$myArray[1] = 'value';
dacer
Forum Newbie
Posts: 5
Joined: Wed Mar 21, 2012 6:08 am

Re: Array declarations

Post by dacer »

don't know if is the best way to do, but I get solved with this line, after Iget how many elements must have my array ($HowManyElements)

Code: Select all

$myArray = array_fill(0, $HowManyElements, '');
With this line I have not errors (warnings) on
/var/log/apache2/error.log

Sl2
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Array declarations

Post by social_experiment »

dacer wrote:I want to create an array, but I don't know how many elements it will have.
Is there a specific reason for this; the size of the array it seems will only be limited by the amount of memory that is allocated for the script

It will be easier to assist you if you can paste the code giving the issues
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply