Jump to content

how to assign values by using loop


xbl1

Recommended Posts

Every index of the array is another array; so if you, for example, wanna put some values on $fruits['d']:

for ($i=0;$i<[number];$i++)	$fruits['d'][$i]=[value];

You do the same with the other indexes

Link to comment
Share on other sites

or maybe you want something like this:

<?php$fruits = Array();for ($i = 'a'; $i <= 'f'; $i++){	$fruits[$i] = "value";}print_r($fruits); ?>

and the result would be

 Array ( [a] => value [b] => value [c] => value [d] => value [e] => value [f] => value)

replace the "value" with your variable where you store fruits

Link to comment
Share on other sites

or maybe you want something like this:
<?php$fruits = Array();for ($i = 'a'; $i <= 'f'; $i++){	$fruits[$i] = "value";}print_r($fruits); ?>

and the result would be

 Array ( [a] => value [b] => value [c] => value [d] => value [e] => value [f] => value)

replace the "value" with your variable where you store fruits

Thanks guys, that's what i want to known.
Link to comment
Share on other sites

or maybe you want something like this:
<?php$fruits = Array();for ($i = 'a'; $i <= 'f'; $i++){	$fruits[$i] = "value";}print_r($fruits); ?>

You know, when you use an if, else, for, while.. etc; if there's only one line to execute, you don't need those { } (I forgot their name in English).You could just write
<?php$fruits = Array();for ($i = 'a'; $i <= 'f'; $i++)	$fruits[$i] = "value";print_r($fruits); ?>

Link to comment
Share on other sites

By the way, this may be relevant, if you want to add an element to the end of an array you can just do

$array[] = "value";

This is the same as

$array[count($array)] = "value";

Link to comment
Share on other sites

Speaking of arrays, someone helped me code an error system using an array, and at the end, when it prints the errors, there's this line.foreach($errors AS $e) echo $eWhy does it need to change the variable for the error array before it prints the contents?
It assigns the current array element to a temporary variable, in this case $e.
Link to comment
Share on other sites

foreach($errors AS $e)echo $eWhy does it need to change the variable for the error array before it prints the contents?
It doesn't *need* to, that's just a shortcut way of doing this:
for ($i = 0; $i < count($errors); i++)  echo $errors[$i];

Link to comment
Share on other sites

Archived

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

×
×
  • Create New...