More elegant way to handle this if statement?

Hi there guys!

I need to set some potential HTML attributes on my page to make sure the proper div element is the one displayed. I wrote this to handle that:

$tab1_1 = $tab1_2 = $tab2_1 = $tab2_2 = $tab3_1 = $tab3_2 = $tab4_1 = $tab4_2 = "";
if(ISSET($_GET['tab']) && IS_NUMERIC($_GET['tab'])){
	$tab = substr($_GET['tab'], 0, 1);
	${'tab'.$tab.'_1'} = " active";
	${'tab'.$tab.'_2'} = " show active";
}

and it works. I’m just curious if there’s a prettier way to handle what I’m doing. I’ve found in my history of muddling, although I’m usually able to get something to work, there’s always a nicer way of doing it so I thought I’d ask.

Thanks for your time!

You could use an array:

$tabs = [];
if (isset($_GET['tab']) && is_numeric($_GET['tab'])) {
	$tab = substr($_GET['tab'], 0, 1);
	$tabs[$tab][1] = " active";
	$tabs[$tab][2] = " show active";
}

and then in the code where you use it if (isset($tabs[$n][1])) { $tabs[$n][1] } or if you’re on PHP 7:

$tabs[$n][1] ?? ''

1 Like

Thanks for the help!

I understand the array and it’s gorgeous but I’m not sure I understand the implementation. In my HTML code, I’ve got 8 places where they are used. If they weren’t defined in the IF, they are blank:

<a class="nav-link'.$tab1_1.'">
stuff
<a class="nav-link'.$tab2_1.'">
stuff
<a class="nav-link'.$tab3_1.'">
stuff
<a class="nav-link'.$tab4_1.'">
stuff

Lots of stuff

<div class="tab-pane fade'.$tab1_2.'">
stuff
<div class="tab-pane fade'.$tab2_2.'">
stuff
<div class="tab-pane fade'.$tab3_2.'">
stuff
<div class="tab-pane fade'.$tab4_2.'">
stuff

I don’t understand how to differentiate between the 4 main groups with your code.

Would become

<a class="nav-link'.($tabs[1][1] ?? '').'">

etc

That makes sense. If it hadn’t been defined in the IF, does the ?? ‘’ set it as blank? It looks like that’s what it’s doing but I just wanted to make sure.

You can learn the details of ?? here:

https://wiki.php.net/rfc/isset_ternary

1 Like

Yes.

$a ?? $b is the same as isset($a) ? $a :$b

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.