Kenneth John Falbous Kenneth John Falbous - 5 months ago 9
PHP Question

Create a loop or array in php for comparing multiple sessions coming from different pages

I have multiple pages and each page has multiple radio buttons which pass values and after checking different selections across all radio buttons output a unique result currently I am creating too many if conditions which is difficult to main, can an array or loop be done for it.

<?php
if(isset($_POST['material'])) {
$_SESSION['material'] = $_POST['material'];

// for screw
if($_SESSION['category'] == "Screw" ) {
if($_SESSION['headtype'] == "Counter Sink Philips") {
if($_SESSION['diameter'] == "6 MM"){
if($_SESSION['length'] == "10 MM"){
if($_SESSION['pitch'] == "1 MM") {
if($_SESSION['material'] == "Brass") {
echo "kenenth start with database";
}
}
}
}
}
}


// for self tapping
if($_SESSION['category'] == "Self Tapping" ) {
if($_SESSION['headtype'] == "Counter Sink Philips") {
if($_SESSION['diameter'] == "6 MM"){
if($_SESSION['length'] == "10 MM"){
if($_SESSION['pitch'] == "1 MM") {
if($_SESSION['material'] == "Brass") {
echo "Self Tapping";
}
}
}
}
}
}

// for stud
if($_SESSION['category'] == "Stud" ) {
if($_SESSION['headtype'] == "Counter Sink Philips") {
if($_SESSION['diameter'] == "6 MM"){
if($_SESSION['length'] == "10 MM"){
if($_SESSION['pitch'] == "1 MM") {
if($_SESSION['material'] == "Brass") {
echo "Stud";
}
}
}
}
}
}

}
?>

Adi Adi
Answer

You could write a recursive function to do that for you:

function in_array_r($find, $yourArray, $strict = false) {
    foreach ($yourArray as $item) {
        if (($strict ? $item === $find : $item == $find) || (is_array($item) && in_array_r($find, $item, $strict))) {
            return true;
        }
    }

    return false;
}

usage

$a['category'] = array("Screw", "Self Tapping", "Stud");
$a['headtype'] = array("Counter Sink Philips", "Counter Sink Philips"));
echo in_array_r($_SESSION['category'], $a) ? 'found' : 'not found';
Comments