I have a form with multiple inputs for one value which have similar names. something like this:
isset($_GET['name1'])
isset($_GET['name2'])
isset($_GET['name3'])
Always, either only one of them is true or none of them. And here is my code:
$name = '';
if( isset($_GET['name1']) ){
$name = $_GET['name1'];
} else if ( isset($_GET['name2']) ) {
$name = $_GET['name2'];
} else if ( isset($_GET['name3']) ) {
$name = $_GET['name3'];
}
echo $name;
My code works as well. But I guess I can do that without those conditions. Any idea how can I write that logic more clean?
You can use a loop:
for ($i = 1; $i <= 3; $i++) {
if (isset($_GET["name$i"])) {
$name = $_GET["name$i"];
break;
}
}
Using the PHP 7 coalescing operator, you can write:
$name = $_GET["name1"] ?? $_GET["name2"] ?? $_GET["name3"] ?? "";
Here's an example how to do it that doesn't necessarily bind you to only the name name
+ 1 through 3
. The order of preference goes from left (most preferable) to right (least preferable), where preferable refers to the order we pick them in.
$names=['name1','name2','name3'];
$name = '';
foreach ($names as $value) {
if (isset($_GET[$value])) {
$name = $_GET[$value];
break;
}
}
echo $name;
Loop through the GET
array and test using empty
$name=false;
foreach( $_GET as $field => $value ){
if( !empty( $value ) ) {
$name=$value;
break;
}
}
Could possibly use the ternary operator for this like below.
$name = $_GET['name1'] ?: $_GET['name2'] ?: $_GET['name3'] ?: '';
which should skip name1 and go to name2 if name1 is empty or isn't set