Re: getting array key with implode
| From: | Brian V Bonini | Date: | Thu, 15 May 2003 20:24:09 +0000 |
| Subject: | Re: getting array key with implode | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-147788@lists.php.net to get a copy of this message | ||
On Thu, 2003-05-15 at 15:48, Ernest E Vogelsinger wrote:
> At 21:46 15.05.2003, Brian V Bonini said:
> --------------------[snip]--------------------
> >How can I get an array key using implode rather then it's value? or
> >perhaps I'm just going about this wrong.
> >
> >
> >while(list($k, $v) = each($_POST)) {
> > $data[$k] = $v;
> >}
> >$required = implode(" || ", $data);
> >if(!$required) {
> > echo "Your missing a field, all field are required for proper
> >calculation";
> >}
> >
> >Thing is I need $data[] 's key not value to make this work.
> --------------------[snip]--------------------
>
> You may use array_keys() to get an arrays of all keys:
> $required = implode(" || ", array_keys($data));
>
> However your testing "if(!$required)" will not work - $required will always
> be set, even if nothing has been entered in your form, for $required being
> always an array, even if empty. You may test "if (!count($required))".
>
> However this will also NOT give you the results you're looking for - the
> test will fail if at least one key has been set... and forms don't transmit
> elements that have not been filled, so these keys are omitted from
> $_REQUEST completely.
So I've found out since last posting..
>
> What do you really want to achieve?
I was just trying to condense this:
if(isset($_POST["do_cal"])) {
// get form input
$multiplier = $_POST['multiplier'];
$weight = $_POST['weight'];
$num_hours = $_POST['num_hours'];
$r_calories = $_POST['r_calories'];
$num_meals = $_POST['num_meals'];
$protein = $_POST['protein'];
$conversion = $_POST['conversion'];
if(!$multiplier || !$weight || !$num_hours || !$r_calories ||
!$num_meals || !$protein
|| !$conversion) {
echo "Your missing a field, all field are required for proper
calculation";
}
with something along these lines
while(list($k, $v) = each($_POST)) {
$data[$k] = $v;
}
$required = array_keys($data);
$required = implode(" || ", $data);
if(!$required) {
echo "Your missing a field, all field are required for proper
calculation";
}