Declare and define array of n elements

Hi,
This is a kind of newbie question, but don’t know why i am not able to get it,
so looking forward for your inputs
do we need to declare something like int a[10],like in c language,before using it ?
i don’t think so.I have read php variables are dynamic so does not need any declaration


<?php
for ($i=1;$i<=10;$i++)
echo $a[$i]."=" .$i . "<br>";
?>

The output it gives is


=1
=2
=3
=4
=5
=6
=7
=8
=9
=10

and what i want is a[1] =1 …a10=10

What you have currently won’t work because your trying to search for an array index which doesn’t exist, see the below example which will output what you want.

for ($i = 0; $i <= 10; $i++) {
    echo "a[$i]=$i<br />";
}

Thanks for quick reply, seems i was bit lazy their :slight_smile:

PHP is a “loosely typed” language. That means, among other things, that the language doesn’t make use care overmuch about the data types of variables. You also do not need to declare them.

Arrays in PHP are, in reality, more like dictionaries in other languages. They are not in any way restricted to being 0 indexed keys. Also, PHP will silently resize the array as you add elements. In fact, you cannot stop PHP from doing this for you, which in some edge cases can be a bit of a pain.

The first time you reference a variable or array key it is initialized - if you don’t give PHP a value it gets set to null. So if you want to create an arracy with ten elements, 1 through 10, ahead of time you can do.


for ($i = 0; $i < 10; $i++ ) {
  $a[] = $i+1;
}

This will create array $a with keys 0-9 and values 1-10. Note that $a wasn’t initialized, and if you have error reporting set to include notices you will get an error. Better then to formally declare that $a will be an array.


$a = array();

But PHP isn’t limited to numerical keys. SQL results typically have keys with names matching their field result from the query, and values matching the field values, like so


$a = array (
  'id' => 1,
  'name' => 'Richard'
  'email' => 'rdoe@gmail.com'
);

PHP started its life as a template engine for binding MySQL results to HTML pages. As a result, it has some of the strongest array traversal and manipulation features of any language. They go far beyond what other languages can do with “arrays” - most other languages need objects of varying types to have the same functionality.

@Michael Morris

PHP started its life as a template engine for binding MySQL results to HTML pages. As a result, it has some of the strongest array traversal and manipulation features of any language. They go far beyond what other languages can do with “arrays” - most other languages need objects of varying types to have the same functionality.

I need to access the following links umpteen times on a daily basis, there are just far too many options to remember :slight_smile:

//