If statement never evaluates to true (even when it should) - php

I'd created an if statement "if ($user_roles == 3) " and this $user_roles has a value of "3" the condition is supposed to be true but the result is always false.
here is my code below:
public function ViewSponsorInfo($sponsor_id)
{
$id = $sponsor_id;
$user_id = User::where('id','=',$id)->get();
$user_roles = [];
foreach ($user_id as $id) {
array_push($user_roles, $id->role);
}/*
dd($user_roles);*/
if ($user_roles == 3) {
$orga = Organization::where('orga_id','=',$sponsor_id)->get();
dd($orga);
return view('pages.Ngo.View-Sponsor-Information',compact('orga'));
}else{
$indi = Individual::where('indi_id','=',$sponsor_id)->get();
dd($indi);
return view('pages.Ngo.View-Sponsor-Information',compact('indi'));
}
}

$user_rolesis not 3 and can never be. it's an array.
its contents, however, can be three.
try:
if(in_array(3, $user_roles)) { ...}
for reference: in_array

$user_roles is an array. So your if statement is always false.

I think, try this one.
foreach ($user_id as $id) {
array_push($user_roles, array('role' => $id->role));
}/*
dd($user_roles);*/
foreach ($user_roles as $user_role) {
if ($user_role['role'] == 3) {
$orga = Organization::where('orga_id','=',$sponsor_id)->get();
dd($orga);
return view('pages.Ngo.View-Sponsor-Information',compact('orga'));
}else{
$indi = Individual::where('indi_id','=',$sponsor_id)->get();
dd($indi);
return view('pages.Ngo.View-Sponsor-Information',compact('indi'));
}
}
or
foreach ($user_id as $id) {
array_push($user_roles, array('role' => $id->role));
}/*
dd($user_roles);*/
foreach ($user_roles as $user_role) {
if ($user_role->role == 3) {
$orga = Organization::where('orga_id','=',$sponsor_id)->get();
dd($orga);
return view('pages.Ngo.View-Sponsor-Information',compact('orga'));
}else{
$indi = Individual::where('indi_id','=',$sponsor_id)->get();
dd($indi);
return view('pages.Ngo.View-Sponsor-Information',compact('indi'));
}
}
Please said something upon it after tried this one.

Judging from what you show your function ViewSponsorInfo() by its very name is only interested in detecting if this user has the sole role '3' in your db.
I mean the outcome is binary isn't it? Either they are a 3 or they are not, no need to go looping thru results.
$user_id = User::where('id','=',$id)->get();
if($user_id[0] !== 3 ) { //***
doSponsorLink();
}else{
doNonSponsorLink();
}
I'm not familiar with Laravel or the db layer your are using, so maybe that is even simply if($user_id).
untested, and here I am assuming user can only have 1 single role, and we do not seem to be making allowances for the user not existing in the db.

Related

rewrite using array filter

How would I write the following foreach with some conditions using array_filter?
foreach ($categories as $category) {
if ($this->request->getParam('category_id')) {
if ($category->getCategoryId() == $this->request->getParam('category_id')) {
$selectedCategory = $category;
break;
}
} else {
No category id in request. Select the first one.
if (array_key_exists(0, $categoryTree) &&
$category->getCategoryId() == $categoryTree[0]['id']
) {
$selectedCategory = $category;
break;
}
}
}
First off, using array_filter isn't helpful in this case as it reduces an array instead of selecting an element. But to show its principles, you could rewrite the code to something like this.
if($this->request->getParam('category_id')){
$filteredCategories = array_filter($categories, function ($category) use ($this){
return $category->getCategoryId() == $this->request->getParam('category_id');
});
if(count($filteredCategories)>0){
return $filteredCategories[0];
}
} else {
[...]
}
I think you want an intersection function and not an array filter.
function key_compare_func($key1, $key2)
{
if ($key1 == $key2->getCategoryId()) {
return 1;
} else {
return 0;
}
}
$selectedCategory = array_intersect_ukey(
$this>request>getParam('category_id'),
$categories,
'key_compare_func'
)
For more information on the different array functions you can look at the PHP manual

PHP: How can i make so non valid users gets another zipfile?

I am really new at php and i came across this code.
Right now it checks for the hwid of a user and grants permission to a zip file if the hwid is in the valid users.
How can i make so the non valid users gets another zipfile to download?
Code:
`
$VALID_USERS = [
'BB12313-25DC-5132-BCEA-B23123123123',
''
];
$IS_REQUEST_ALLOWED = false;
if(!isset($_POST['hwid']) && !isset($_GET['hwid'])) { die(); }
$USER_HWID = '0';
if(isset($_POST['hwid'])) {
$USER_HWID = $_POST['hwid'];
} else {
$USER_HWID = $_GET['hwid'];
}
$USER_HWID = trim($USER_HWID);
$USER_HWID = strtoupper($USER_HWID);
foreach($VALID_USERS as $USER) {
$USER = strtolower($USER);
$HWID = strtolower($USER_HWID);
if($HWID === $USER) {
readfile('./ZIPFILE.zip'); die();
}
}
`
Assuming other code functions properly, your if clause at the end should look like this:
if($HWID === $USER) {
readfile('./ZIPFILE.zip'); die();
} else {
readfile('OtherFile.zip'); die();
}
After you compare $HWID === $USER, offer a different file in the ELSE added below.
foreach($VALID_USERS as $USER) {
$USER = strtolower($USER);
$HWID = strtolower($USER_HWID);
if($HWID === $USER) {
readfile('./ZIPFILE.zip'); die();
} else { //not a valid user
readfile("./invalid_file.zip");die();
}
}
Note that this will give "invalid_file.zip" to anyone who doesn't meet the criteria ($HWID===$USER) (maybe, see below).
Also, die() is rather a nasty way to exit (it doesn't even tell the user why it's leaving ...).
Please also take a look at your $VALID_USERS array. Surely you don't mean to have a null value in there?
Finally, what about the case of someone else who isn't null or "BB12313-25DC-5132-BCEA-B23123123123"?
You might wish to reconsider the use of this code.
Replace your entire foreach loop with this one if block. Since you are keeping your VALID_USERS in an array, you can use in_array() to quickly check if you user is there, the loop is unnecessary.
This:
foreach($VALID_USERS as $USER) {
$USER = strtolower($USER);
$HWID = strtolower($USER_HWID);
if($HWID === $USER) {
readfile('./ZIPFILE.zip'); die();
}
}
Becomes:
if (in_array($USER_HWID, $VALID_USERS, true)) {
readfile('./ZIPFILE.zip'); die();
} else {
readfile('./SomeOtherZIPFILE.zip'); die();
}
You will also notice that the 3rd paramter to in_array() has been set true in this example. This enables strict type comparison, to match the original codes '===' check.

If Else Echo JSON array check

I have a JSON array that I am pulling values from per $vars. Within the JSON data are going to be some key words that I am looking for. I have a single if else that looks like:
(demonstration purposes)
if( $FullName == $Data[$c]['manager'] $FullName == $Data[$c]['leader'] || $FullName == $Data[$c]['helper']) {
$cheapLabor = 'NO';
} else {
$cheapLabor = 'YES';
}
That works great however, now I want to define more specifically some if else points on status points which would represent their employement status. Each Emp Status is based on a group.
I would need it to check from the top of the food chain, then go downward to check if status = x. If it does then $cheapLabor = 'y'; else $cheapLabor = 'z';
I tried doing it, but I can't seem to get it to work. Here is what I am working with:
$repData = json_decode($json, TRUE);
$c = 0;
$var = $repData[$c]['column'];
if($FullName == $repData[$c]['ceo']) {
$groups = '[13]';
} else {
$groups = '[5]';
}
if($FullName == $repData[$c]['director']) {
$groups = '[10]';
} else {
$groups = '[5]';
}
if($FullName == $repData[$c]['regional']) {
$groups = '[9]';
} else {
$groups = '[5]';
}
if($FullName == $repData[$c]['project_manager']) {
$groups = '[8]';
} else {
$groups = '[]';
}
if($FullName == $repData[$c]['team_leader']) {
$groups = '[6]';
} else {
$groups = '[5]';
}
if($FullName == $repData[$c]['rae']) {
$groups = '[5]';
} else {
$staus = '[5]';
}
Shomz Answer partial working...
$groups = '[4]'; // new hire group default, to be overwritten if a user has the correct title within Table.
$roleGroups = array(
'regional' => '[7]',
'team_leader' => '[6]',
'RAE' => '[5]'
);
foreach ($roleGroups as $role => $groups) { // go through all the Position Titles
if ($FullName == $repData[$c][$role]) { // see if there's a match
$repGroup = $groups; // if so, assign the group
}
}
It sets team_leader and regional correctly but anything else just sets it as regional group.
Just realized that its actually rewriting the value.
Your code is overwriting $groups in every if-statement. You probably want to rewrite that in a switch/case statement with a default value being [5].
Let's say the first if is true, so $FullName == $repData[$c]['ceo'] is true and $groups becomes [13]. In the next line, there are two choices:
either a person is a director (AND a CEO, but it doesn't matter, see why below)
or a person is not a director (could be a CEO)
In both cases, $groups will either get a value of [10] or [5], meaning that no matter what happened inside the statement above, this statement will overwrite it. Thus, only your last if statement is able to produce results you might expect.
"Only one group per role"
In that case a simple switch/case statement will work:
switch($FullName){
case ($repData[$c]['ceo']):
$groups = '[13]';
break;
case ($repData[$c]['director']):
$groups = '[10]';
break;
// etc... for other roles
default:
$groups = '[5]';
break;
}
Or you can go even simpler and use an associative array to combine roles with group numbers. For example:
$roleGroups = array('ceo' => '[13]', 'director' => '[15]', etc);
Then simply see if there's a match:
$groups = '[5]'; // default, to be overwritten if a role is found below
foreach ($roleGroups as $role => $group) { // go through all the groups
if ($FullName == $repData[$c][$role]) { // see if there's a match
$groups = $group; // if so, assign the group
}
}
Hope this makes sense. Either way, $groups will have the number of the role if role is found, 5 otherwise.

How can I place text that relates to a foreach function, outside the loop?

I'm really unsure how to describe this, so please forgive me.
Basically, I'm reading from an XML, and then generating an IF statement that checks all records in the XML and if a condition matches, details about that record is displayed.
What I want to add, is a similar function but in reverse, but outside the foreach loop, so it's only displayed once.
foreach($xml as $Reader) { $items[] = $Reader; }
$items= array_filter($items, function($Reader) use ($exclude) {
if($Reader->Picture == 'None' || in_array($Reader->Pin, $exclude)) {
return false;
}
return true;
});
usort ($items, function($a, $b) {
return strcmp($a->Status,$b->Status);
});
foreach($items as $Reader) {
if($Reader->Status == 'Available' && !in_array($Reader->Pin, $exclude)) {
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
}
}
if (!$items) { echo "Please check back in a moment when our readers will be available!"; }
So, in the XML file each Reader has a Status that can be one of three values: Available, Busy or Logged Off.
So what I'm doing, is for each record in the XML, checking if the Reader status is available.. and if so, echo the above line.
But I want to add in, that if NONE of the readers show as 'Available' to echo a single line that says 'Please check back in a moment'.
With the code above, ifthere are four readers online, but they're all busy.. nothing is displayed.
Any ideas?
Just use a simple boolean value
$noneAvailable = true;
foreach($items as $Reader) {
if($Reader->Status == 'Available' && !in_array($Reader->Pin, $exclude)) {
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
$noneAvailable = false;
}
}
if ($noneAvailable) {
echo "Please check back in a moment";
}
I managed to take the answer given above, and combine it with XPath to just filter the records in the XML based on the status given using xPath.
include TEMPLATEPATH."/extras/get-readers.php";
$readers = $xml->xpath('/ReaderDetails/Reader[Status="Available"]');
$gotOps = false;
foreach ($readers as $Reader)
{
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
$gotOps = true;
}
if ($gotOps!=true)
{
echo 'Please check back in a moment when our readers will be available!';
}

Conditional array in PHP

This is my code
foreach($orders as $order) {
array_push($list, array($order['name'],$order['email'],$order['financial_status']));
}
Now i got the value of financial_status is 1, I want to get value as true. I want to add condition before the foreach loop.
Can anyone help me? Thanks in advance!.
You need this maybe:
foreach($orders as $order) {
if ($order['financial_status'] == 1){
$financial_status = true;
} else {
$financial_status = false;
}
array_push($list, array($order['name'],$order['email'],$financial_status));
}
It will put boolean in array.
foreach($orders as $order) {
if ($order['financial_status'] == 1){
return true
} else {
return false
}
array_push($list, array($order['name'],$order['email'],$financial_status));
}
check this edit
make sure to comparing with financial_status in table
if you want financial_status to return true when its value is 1 in sql and if true value required to be a different value change ==1 to that value

Categories