Link to home
Create AccountLog in
Avatar of dsrnu
dsrnu

asked on

Improve logic of code (foreach)

Hi everyone,

Any ideas on how I might improve my code below?

		$page_staff_value = false;
		foreach($res_array as $list)
		{
			if ($list['rights'] == 'page_staff')
			{
				$page_staff_value = true;
				break;
			}
		}
		$data['page_staff_value'] =  $page_staff_value;
		
		$page_earnings_value = false;
		foreach($res_array as $list)
		{
			if ($list['rights'] == 'page_earnings')
			{
				$page_earnings_value = true;
				break;
			}
		}
		$data['page_earnings_value'] =  $page_earnings_value;

Open in new window

Avatar of cyberkiwi
cyberkiwi
Flag of New Zealand image

           $page_staff_value = false;
            $page_earnings_value = false;
            foreach($res_array as $list)
            {
                  if ($list['rights'] == 'page_staff')
                  {
                        $page_staff_value = true;
                  }
                  elseif ($list['rights'] == 'page_earnings')
                  {
                        $page_earnings_value = true;
                  }
                  if ($page_staff_value && $page_earnings_value) {break;}
            }
            $data['page_staff_value'] =  $page_staff_value;
            $data['page_earnings_value'] =  $page_earnings_value;
SOLUTION
Avatar of cyberkiwi
cyberkiwi
Flag of New Zealand image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
I would be tempted to do it like this:
function has_right($right) {
	$res_array = ???;
	foreach ($res_array as $list)
		if ($list['rights'] == $right)
			return true;
	return false;
}

if (has_right('page_staff')) {
    // Do something!
}
else if (has_right('page_earnings')) {
    // Do something!
}

Open in new window

Or cleaner still:
class User {

	$rights = array();

	function add_right($right) {
		$rights[$right] = true;
	}

	function remove_right($right) {
		unset($rights[$right]);
	}

	function has_right($right) {
		return isset($rights[$right]) && $rights[$right] === true;
	}

}

if ($user->has_right('page_staff')) {
	// Do something!
}
else if ($user->has_right('page_earnings')) {
	// Do something!
}

Open in new window

ASKER CERTIFIED SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account