Reputation: 5614
Basically I want to add the following information to a single database field, (The txt-via-hn textboxes are house numbers, the txt-via are address details)
$vias = $_POST['txt-via-hn2'].' '.$_POST['txt-via2']
.' -> '.$_POST['txt-via-hn3'].' '.$_POST['txt-via3']
.' -> '.$_POST['txt-via-hn4'].' '.$_POST['txt-via4']
.' -> '.$_POST['txt-via-hn5'].' '.$_POST['txt-via5']
.' -> '.$_POST['txt-via-hn6'].' '.$_POST['txt-via6']
.' -> '.$_POST['txt-via-hn7'].' '.$_POST['txt-via7']
.' -> '.$_POST['txt-via-hn8'].' '.$_POST['txt-via8']
.' -> '.$_POST['txt-via-hn9'].' '.$_POST['txt-via9']
.' -> '.$_POST['txt-via-hn10'].' '.$_POST['txt-via10'];
At the moment, for example, if I were to enter two vias the following would be added to the database field:
HOUSENUMBER ADDRESS -> HOUSENUMBER ADDRESS -> -> -> -> -> -> ->
What I want to happen is if the text box value is empty, to not include the empty spaces at the end. So if I was to enter just two vias, only the following would be added:
HOUSENUMBER ADDRESS -> HOUSENUMBER ADDRESS
Is this possible?
Upvotes: 0
Views: 454
Reputation: 59699
Add them all to an array, run array_map()
and array_filter()
on them to get rid of empty elements, then implode()
them, like so:
$array = array();
foreach( range( 2, 10) as $i) {
$array[] = $_POST['txt-via-hn' . $i] . ' ' . $_POST['txt-via' . $i];
}
$vias = implode( ' -> ', array_filter( array_map( 'trim', $array)));
You could even check for empty values in the loop, and omit the call to array_filter()
, like so:
$array = array();
foreach( range( 2, 10) as $i) {
if( !empty( $_POST['txt-via-hn' . $i]) && !empty( $_POST['txt-via' . $i]))
$array[] = $_POST['txt-via-hn' . $i] . ' ' . $_POST['txt-via' . $i];
}
$vias = implode( ' -> ', $array);
Note that both approaches will yield notices if you attempt to access an index within $_POST
if it isn't defined. To rectify this, call isset()
before you attempt to read from $_POST
to make sure the key is set.
Upvotes: 2
Reputation: 8578
for($i = 2; $i <= 10; $i++)
{
if(strlen($_POST['txt-via2']))
$array[] = $_POST['txt-via-hn'.$i] . ' ' . $_POST['txt-via'.$i];
}
$vias = join("->", $array);
Upvotes: 0