I have an array that uses two codes in a list and pushes them into a form on the next page. Currently I have:
$code= array();
$code['c1'] = substr($part, 0, 1);
$code['c2'] = substr($part, 2);
Now, If I select anything with a single digit c1
and single or double c2
then it adds to the form.
Examples:
1-9
1-15
9-12
9-9
But if I try to add anything with double digits in c1 it doesn't add, like:
10-1
10-2
10-11
If I try
$codes= array();
$codes['c1'] = substr($part, 0, 2);
$codes['c2'] = substr($part, 2);
Then no codes show up.
How can I account for both?
UPDATE:
Currently, the above code, if I select 10-58, will dump c1 as 1 and c2 as -5
You can easily use explode()
and list()
to split any combination of codes...
$part = "1-15";
$codes = array();
list($codes['c1'], $codes['c2']) = explode("-", $part);
print_r($codes);
gives...
Array
(
[c1] => 1
[c2] => 15
)
For
$part = "10-15";
it gives...
Array
(
[c1] => 10
[c2] => 15
)
If you are unsure if your data is always correct, you can check that the data has 2 components after using explode()
and only convert it then, you can also do something to report and error or whatever you need...
$split = explode("-", $part);
if ( count($split) == 2 ){
$codes['c1'] = $split[0];
$codes['c2'] = $split[1];
}
else {
// Not of correct format.
}
print_r($codes);