KevinM1990112qwq KevinM1990112qwq - 7 months ago 10
PHP Question

Can I shorten/Clean up this code

I am really annoyed by having this much IF, Else If statements.... Is there a way to shorten this up and make it look cleaner, nicer but still have the same effect?

if(!empty($ck1))
{
$ck1 = 'Tiger';
}
else
{
$ck1 = '';
}


if(!empty($ck2))
{
$ck2 = 'Bears';
}
else
{
$ck2 = '';
}
if(!empty($ck3))
{
$ck3 = 'Owls';
}
else
{
$ck3 = '';
}

Answer

Something like that perhaps is cleanest, assuming you need different default values.

$vars = array(
    'ck1' => 'Tiger',
    'ck2' => 'Owl',
    ...
    'ck36' => 'Foo'
    );
foreach($vars as $var=>$default) {
    $$var = !empty($$var) ? $default : '';
}

You can use for and build $var dynamically, but it'd be painful to deal with default values (especially edits would lead to errors, sooner than later), so it's not worth.

EDIT

$vars array holds variable name you want to work on as key, and default value as value. So you can have as many as you like there.

EDIT 2

Beware of variable scopes. Also you said that cks come from Check boxes on a form. If so, then it means you got register_globals enabled? If so, it's bad idea and you should disable it ASAP.

EDIT 3

Instead of having tons of variables, you should keep them organized as array, by using [] in variable name tag:

<input name="ck[]" value="Foo">
<input name="ck[]" value="Bar">

then all inputs (in case of checkbox, all checked of course) can be easily found in $_POST['ck']. You can also add own index if you want to then look easily for particular item:

<input name="ck[foo]" value="Foo">

is available as $_POST['ck']['foo']. That would allow to make your code cleaner, i.e.:

$input = $_POST['ck'];

$vars = array(
    'ck1 => 'Tiger',
    'ck2' => 'Owl,
    ...
    'ck36' => 'Foo'
    );
foreach($vars as $key=>$default) {
    $input[$key] = !empty($input[$key]) ? $default : '';
}

end then you can use $input further in your code, w/o having tons of variables in the script scope.