Reputation: 922
Okay, so all my code is working, I just want to know if there's a simpler way to do it. The code:
if($_POST['A'] == ""){echo "A";}
if($_POST['B'] == ""){echo "B";}
if($_POST['C'] == ""){echo "C";}
if($_POST['A'] == "" && $_Post['B'] == ""){echo "A and B";}
if($_POST['A'] == "" && $_Post['C'] == ""){echo "A and C";}
if($_POST['B'] == "" && $_Post['C'] == ""){echo "B and C";}
Now, what I want to know is rather simple, is there any way to make this simpler? It works fairly well with three variables, but if I were to (for example) circle the whole alphabet, if my memory regarding statistics is correct, it'd be 26! which is equal to 4.0329146e+26. Hell, even circling the first 7 letters, 7! is 5040 possible combinations I'd have to code.
What I'm looking for is something that doesn't exactly have to echo "A and B", but if A is the only thing posted to echo A; if A and B are posted to echo "A" and "B" and to echo an "and" between them; and if A, B, and C are posted to echo "A", "B" and "C" and to echo a "," between the first two and to echo an "and" between the second to last and the last.
I don't know if I'm wanting a function, or a class, or something else. This is probably a simple question in the end run, if so, please forgive my ignorance.
Upvotes: 0
Views: 306
Reputation: 15706
function format_list( $items )
{
if ( count( $items ) == 0 )
return '';
if ( count( $items ) == 1 )
return $items[0];
$last_item = array_pop( $items );
$list_text = join( ', ', $items ) . ' and ' . $last_item;
return $list_text;
}
$items = array();
$keys = array( 'A', 'B', 'C' );
foreach ( $keys as $key )
{
if ( !empty( $_POST[$key] ) )
$items[] = $key;
}
echo format_list( $items );
Upvotes: 1
Reputation: 505
$count = count($_POST);
$a = 1;
$str = '';
foreach ( $_POST as $key => $value )
{
// if u wanna use values just replace $key to $value
if ( $count > $a++ )
$str .= $key . ', ';
else
{
$str = rtrim( $str, ', ' );
$str .= ' and ' . $key;
$str = ltrim( $str, ' and ' );
}
}
Upvotes: 0
Reputation: 14931
For a simple message like "A and B", the following would do the job:
$variables = range('A', 'Z');
echo implode(' and ', $variables);
If you have a $_POST you could do the following:
if($_POST){
echo implode(' and ', array_keys($_POST));
}
Upvotes: 2