views:

87

answers:

3

In my validation class I have this:

    $fields['a_1'] = 'First Question';
    $fields['a_2'] = 'Second Question';
    $fields['a_3'] = 'Third Question';
    $fields['a_4'] = 'Fourth Question';

This is getting old--I have about 40 of these to write, and each set has matching validation rules:

    $rules['a_1'] = 'hour';
    $rules['a_2'] = 'hour';
    ...

Is there a way to say:

$fields['a_' . 1 - 17] = "One, Two"

Etc...

Just curious... if not, I'll brute force it.

A: 

Can you just use a foreach loop with a range, as shown on this page?

foreach (range(1, 17) as $i) {
   $fields['a_' . $i] = "One, Two";
}

Or if you need to refer to values in another array:

$other_array = ("some", "other", "values");
foreach (range(1, count($other_array)) as $i) {
   $fields['a_' . $i] = $other_array[$i+1];
}
Kaleb Brasee
$other_array.length in PHP?? that second snippet is a hybrid of javascript and PHP
pǝlɐɥʞ
Yeah, that's right, thanks -- haven't used PHP in a few years. Why they'd make it a language keyword instead of an object method is beyond me. But it *is* PHP, LOL.
Kaleb Brasee
no probs, also while you are editing... you do not define arrays with square brackets in PHP, should be $other_array = array("some", "other", "values");
pǝlɐɥʞ
+1  A: 

you can try this

$ar=array("One","Two","Three");

for($i=1;$i<18;$i++){
  $fields["a_".$i]=$ar[$i];
}

where $ar contains the list of values you want to assign in order

pǝlɐɥʞ
A: 

You might see if you can't change the question. $foo['a_1'] is often better written as $foo['a'][1] - this will make both construction and working with them easier -- foreach($foo['a'] as $item) do_stuff($item); is much easier than something like for($i=0; $i<$stop; $i++) do_stuff($foo['a_'.$i]);, and you can then using the array to store the validation rule (and any other relationship) alongside the item itself:

$foo['a'] = array(array('fieldname' => 'First Question', 'rule' => 'hour'));
TML
What you're trying to communicate is a bit above me...
Kevin Brown
If you're inclined, you could join ##PHP on irc.freenode.net and find me (TML), I'd be more than happy to try and explain this. I really think it would save you some time and improve the overall readability of your code.
TML