Related
Hello guys i have a code that receive values from the another page and i want to check if the value equal with on of one values in the array then give me that value so this is my code :
**<?php
session_start();
ob_start();
//where we get data from the form
if (isset($_POST["btn"])){
$name=$_POST["name"];
$number=$_POST["number"];
$date=$_POST["fd"].'/'. $_POST["sd"].'/' .$_POST["td"];
echo $name;
echo"</br>";
echo $number;
echo"</br>";
echo $date;
}
$ar=sscanf($date,"%d/%d/%d");
$month1=$ar[1]; // for example the value is 5
from the here i have array
$month=array(
"juan" =>"1",
"feb" =>"2",
"march" =>"3",
"april" =>"4",
"may" =>"5",
"jun" =>"6",
"july" =>"7",
"agu" =>"8",
"sep" =>"9",
"oct" =>"10",
"nov" =>"11",
"dec" =>"12"
);
function monthdate($m,$m1){
$flag=false;
foreach ($m1 as $key=>$val){
$val1=$val;
if ($val1 == $m){
$flag=true;
break;
}
else if(!$val1 == $m) {
$flag=false;}
}
if($flag == true ){
echo $val1;}
}
echo "your birthday month is ". monthdate($month1,$month);
echo"</br>";
?>**
why the function doesn't give me any data ?
This is a very strange condition, and probably isn't what you think it is:
if(!$val1 == $m)
You're negating $val1 (which may not do what you think it does for non-boolean values) and comparing the result of that with $m. Surely you meant this?:
if($val1 != $m)
Though, even still, you don't need this condition at all. Your original if is comparing these values:
if ($val1 == $m)
Following that, all cases where they do not equal will move to the else block. There's no need for an explicit if on that else block if it just repeats the negative of the original if condition.
Even further, your else condition likely isn't necessary in this function at all. Consider the logic you're implementing... A value is false until the first matching result is found, then it's true and the loop (and function) completes and exits. There's no reason to ever reset the value to false, so the entire else block is unnecessary.
Aside from that, based on your usage of the function it looks like you had meant to return $val1 instead of echo $val1. In the code you're using the two approaches are likely to produce identical results so it may make no difference here, but it's important to understand the difference between the two or you're sure to encounter strange bugs in the future.
Edit: Based on your comment below, it sounds like you also want some kind of default value for input which doesn't match the data. You still don't necessarily need the else, you can rely on control flow at the end of your function. For example, where you currently have this:
if ($flag == true){
echo $val1;
}
You could do this:
if ($flag == true){
echo $val1;
} else {
echo "Not found!";
}
Or, if you switch to return instead of echo as suggested above, you could do the same with slightly less code:
if ($flag == true){
return $val1;
}
return "Not found!";
Or even:
return $flag == true ? $val1 : "Not found!";
You can directly parse the loop and when loop gets the required month
and monthname, you can directly break the loop or you can return from
the function
<?php
$month1=5;
$month=array(
"juan" =>"1",
"feb" =>"2",
"march" =>"3",
"april" =>"4",
"may" =>"5",
"jun" =>"6",
"july" =>"7",
"agu" =>"8",
"sep" =>"9",
"oct" =>"10",
"nov" =>"11",
"dec" =>"12"
);
function monthdate($m, $m1)
{
foreach ($m1 as $key => $val)
{
if ($val == $m)
{
return $key;
}
}
}
echo "Your birthday month is " . monthdate($month1, $month);
?>
But in my opinion, using ID is a better option with respect to words for comparison.You can achieve the same above result like:
<?php
$month1=5;
$month = array(
"1"=>"jan",
"2"=>"feb",
"3"=>"mar",
"4"=>"apr",
"5"=>"may",
"6"=>"jun",
"7"=>"jul",
"8"=>"aug",
"9"=>"sep",
"10"=>"oct",
"11"=>"nov",
"12"=>"dec"
);
function monthdate($m, $m1)
{
foreach ($m1 as $key => $val)
{
if ($key == $m)
{
return $val;
}
}
}
echo "Your birthday month is " . monthdate($month1, $month);
?>
If you have the option to select value greater than 12,
<?php
$month1=5;
$month=array(
"juan" =>"1",
"feb" =>"2",
"march" =>"3",
"april" =>"4",
"may" =>"5",
"jun" =>"6",
"july" =>"7",
"agu" =>"8",
"sep" =>"9",
"oct" =>"10",
"nov" =>"11",
"dec" =>"12"
);
function monthdate($m, $m1)
{
$flag='';
foreach ($m1 as $key => $val)
{
if ($val == $m)
{
$flag=$key;
break;
}
}
return $flag;
}
$d = monthdate($month1, $month);
if(trim($d)==null)
{
echo 'Not found';
}
else
{
echo "Your birthday month is " .$d ;
}
?>
$month=array(
"juan" =>"1",
"feb" =>"2",
"march" =>"3",
"april" =>"4",
"may" =>"5",
"jun" =>"6",
"july" =>"7",
"agu" =>"8",
"sep" =>"9",
"oct" =>"10",
"nov" =>"11",
"dec" =>"12"
);
function Search($value, $array)
{
return(array_search($value, $array));
}
$entered_month= '13';
if($entered_month > 0 && $entered_month <=12){
echo "your birthday month is ". Search($entered_month,$month);
echo"</br>";
}else{
echo "Please enter a valid months";
echo"</br>";
}
I am comparing seven (7) boolean values 1 (true) or 0 (false) of a primary set and five (5) of a secondary set with an addition of 2 n/a choices. If all 12 come back as true, then the $class is set to Reuse. If the primary set is True and Secondary is false then it comes back as Resale. If any of the primary set comes back False, it's set to Repair. This is what I have so far, and don't get back any syntax errors, but the "class" is coming back incorrect.
<?php
$primary = false;
$class = null;
if ($_POST['poweradapter'] == "1"
&& $_POST['mobocpu'] == "1"
&& $_POST['memory'] == "1"
&& $_POST['harddrive'] == "1"
&& $_POST['screen'] == "1"
&& $_POST['battery'] == "1"
&& $_POST['hinge'] == "1")
{
$class = "Reuse";
$primary = true;
}
else
{
$class = "Repair or Recycle";
}
if ($primary
&& in_array($_POST['opticaldrive'], ["1", "2"])
&& in_array($_POST['floppydrive'], ["1", "2"])
&& $_POST['usb'] == "1"
&& $_POST['trackpad'] == "1"
&& $_POST['keyboard'] == "1")
{
/*
* "secondary" is implicit here, but we never did anything with the
* $secondary variable in the original script
*/
$class = "Reuse";
}
else
{
$class = ($primary) ? "Reuse" : "Repair or Recycle";
}
?>
Final working script
<?php
$primary = false;
$class = null;
if ($_POST['poweradapter'] == "1"
&& $_POST['mobocpu'] == "1"
&& $_POST['memory'] == "1"
&& $_POST['harddrive'] == "1"
&& $_POST['screen'] == "1"
&& $_POST['battery'] == "1"
&& $_POST['hinge'] == "1")
{
$primary = true;
$class = "Resale";
}
else
{
$class = "Repair or Recycle";
}
if ($primary && in_array($_POST['opticaldrive'], ["1", "2"])
&& in_array($_POST['floppydrive'], ["1", "2"])
&& $_POST['usb'] == "1"
&& $_POST['trackpad'] == "1"
&& $_POST['keyboard'] == "1")
{
$class = "Reuse";
}
?>
The main problem is that you're using double equals in the body of the first if statement.
$class == "Reuse";
$primary == "True";
should be
$class = "Reuse";
$primary = "True";
There are a lot of things you could do to make this more readable and maintainable, but the bug is the equality vs assignment issue.
Here is what I would do to make this easier to work with:
<?php
$primary = false;
$class = null;
if ($_POST['poweradapter'] == "1"
&& $_POST['mobocpu'] == "1"
&& $_POST['memory'] == "1"
&& $_POST['harddrive'] == "1"
&& $_POST['screen'] == "1"
&& $_POST['battery'] == "1"
&& $_POST['hinge'] == "1")
{
$class = "Reuse";
$primary = true;
}
else
{
$class = "Repair or Recycle";
}
if ($primary
&& in_array($_POST['opticaldrive'], ["1", "2"])
&& in_array($_POST['floppydrive'], ["1", "2"])
&& $_POST['usb'] == "1"
&& $_POST['trackpad'] == "1"
&& $_POST['keyboard'] == "1")
{
/*
* "secondary" is implicit here, but we never did anything with the
* $secondary variable in the original script
*/
$class = "Reuse";
}
else
{
$class = ($primary) ? "Resale" : "Repair or Recycle";
}
Hope this helps.
[Edit]
Since you're still having trouble with the logic itself, this is an ideal case for unit testing. Here's a little script you can run from the command line to test and fine tune your logic without having to worry about getting PHPUnit set up:
<?php
class MyService
{
public static $CLASS_REUSE = 'Reuse';
public static $CLASS_RESALE = 'Resale';
public static $CLASS_REPAIR_RECYCLE = 'Repair or Recycle';
public static function determineClassForInputParameters($params)
{
$primary = false;
$class = null;
if ($params['poweradapter'] == "1"
&& $params['mobocpu'] == "1"
&& $params['memory'] == "1"
&& $params['harddrive'] == "1"
&& $params['screen'] == "1"
&& $params['battery'] == "1"
&& $params['hinge'] == "1")
{
$primary = true;
}
if ($primary
&& in_array($params['opticaldrive'], ["1", "2"])
&& in_array($params['floppydrive'], ["1", "2"])
&& $params['usb'] == "1"
&& $params['trackpad'] == "1"
&& $params['keyboard'] == "1")
{
$class = self::$CLASS_REUSE;
}
else
{
$class = ($primary) ? self::$CLASS_RESALE : self::$CLASS_REPAIR_RECYCLE;
}
return $class;
}
}
class MyServiceTest
{
public function __construct()
{
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);
assert_options(ASSERT_CALLBACK, array($this, 'assertHandler'));
}
public function determineClassForInputParametersShouldReturnReuse()
{
$params = [
'poweradapter' => 1,
'mobocpu' => 1,
'memory' => 1,
'harddrive' => 1,
'screen' => 1,
'battery' => 1,
'hinge' => 1,
'opticaldrive' => 1,
'floppydrive' => 1,
'usb' => 1,
'trackpad' => 1,
'keyboard' => 1
];
$class = MyService::determineClassForInputParameters($params);
if (assert($class == MyService::$CLASS_REUSE, 'Expected class ' . MyService::$CLASS_REUSE . ', found ' . $class))
{
echo "determineClassForInputParametersShouldReturnReuse Passed\n";
}
}
public function determineClassForInputParametersShouldReturnResale()
{
$params = [
'poweradapter' => 1,
'mobocpu' => 1,
'memory' => 1,
'harddrive' => 1,
'screen' => 1,
'battery' => 1,
'hinge' => 1,
'opticaldrive' => 1,
'floppydrive' => 1,
'usb' => 1,
'trackpad' => 1,
'keyboard' => 0
];
$class = MyService::determineClassForInputParameters($params);
if (assert($class == MyService::$CLASS_RESALE, 'Expected class ' . MyService::$CLASS_RESALE . ', found ' . $class))
{
echo "determineClassForInputParametersShouldReturnResale Passed\n";
}
}
public function determineClassForInputParametersShouldReturnRePairOrRecycle()
{
$params = [
'poweradapter' => 0,
'mobocpu' => 1,
'memory' => 1,
'harddrive' => 1,
'screen' => 1,
'battery' => 1,
'hinge' => 1,
'opticaldrive' => 1,
'floppydrive' => 1,
'usb' => 1,
'trackpad' => 1,
'keyboard' => 1
];
$class = MyService::determineClassForInputParameters($params);
if (assert($class == MyService::$CLASS_REPAIR_RECYCLE, 'Expected class ' . MyService::$CLASS_REPAIR_RECYCLE . ', found ' . $class))
{
echo "determineClassForInputParametersShouldReturnRePairOrRecycle Passed\n";
}
}
public function assertHandler($file, $line, $code, $desc = null)
{
echo "Assertion failed at $file:$line: $code";
if ($desc)
{
echo ": $desc";
}
echo "\n";
}
}
$tester = new MyServiceTest();
$tester->determineClassForInputParametersShouldReturnReuse();
$tester->determineClassForInputParametersShouldReturnResale();
$tester->determineClassForInputParametersShouldReturnRePairOrRecycle();
You may find it useful to adopt some of the techniques shown in the test, like encapsulating your logic in a service class to make it easier to test and use in multiple places, using static variables for your "class" names to prevent typo errors, etc. Or you can just tune your logic with this and copy it into your existing code.
It may seem like a lot of overhead, but the few minutes it takes to set up tests for your logic far outweighs the hours you can waste trying to figure it out by submitting requests through your front end.
Here try to first set primary and secondary flag to true or false, then compare for the conditions, below is the code snippet, hope this helps.
There are two problems
1. in the first if you are setting $primary as $primary == "True" instead of $primary="True" , so here instead of setting the primary flag, it is comparing whether $primary is true. same is the case with $class.
in the second if statement -$_POST['floppydrive']=="1" or"2" is always true , so it results in true block of if getting executed every time, here or "2", can be changed to - ($_POST['floppydrive']=="1" || $_POST['floppydrive']=="2")
This should get you desired result
<?php
//setting primary flag
if ($_POST['poweradapter']=="1" && $_POST['mobocpu']=="1" && $_POST['memory']=="1" && $_POST['harddrive']=="1" && $_POST['screen']=="1" && $_POST['battery']=="1" && $_POST['hinge']=="1"){
$primary = "True";
}else{
$primary = "False";
}
//setting secondary flag
if (($_POST['opticaldrive']=="1" || $_POST['opticaldrive']== "2") && ($_POST['floppydrive']=="1" || $_POST['floppydrive']== "2") && $_POST['usb']=="1" && $_POST['trackpad']=="1" && $_POST['keyboard']=="1"){
$secondary = "True";
}else{
$primary = "False";
}
//setting the class now
if ($primary == "True" && $secondary=="True") {
$class = "Reuse";
}
elseif ($primary == "True" && $secondary=="False") {
$class = "Resale";
}
else{
$class = "Repair or Recycle";
}
?>
output
Power Adapter: 1
Motherboard: 1
Memory: 1
Hard/SSD Drive: 1
Screen: 1
Battery: 0
Screen Hinge: 0
USB Ports: 0
Track/Touch Pad: 0
Keyboard: 0
Optical Drive: 0
Floppy Drive: 1
was added with an Class of Repair or Recycle
when I do this in CgridView:
'value' => '$data->status == 1 ? "Payed" : "None" ',
it works, but when I do this:
'value' => 'if ($data->status == 1) { echo "Payed"; } else if($data->status == 2) { echo "Two"; } else { echo "None"; } '.
What I need to do to make work the second statement, or how I need to rewrite it?
Convert your statement to use ternary if:
'value' => '$data->status == 1 ? "Payed": ($data->status == 2 ? "Two" : "None")',
You could also use a function instead to give a bit more flexibility and make it more readable:
'value' => function($row, $data ) {
if ($data->status == 1) { return "Payed"; }
else if($data->status == 2) { return "Two"; }
else { return "None"; }
}
Just in case :
I've tried topher's solution and I found out that I had to switch param like that :
'value' => function($data, $row ) {
if ($data->status == 1) { return "Payed"; }
else if($data->status == 2) { return "Two"; }
else { return "None"; }
}
With topher's solution $data->attribute_name did not work and was, in fact, the row instead of the model..
Perhaps, if you don't need $row, don't pass it.
my solution:
function checkStatus($status)
{
if ($status == 1) {
return "opl";
} else if ($status == 2) {
return "nal";
} else {
return "neopl";
}
}
'value' => 'checkStatus($data->status)',
But your will work too) I will accept answer)
I need to put a condition when I create one element of my array
foreach ($score as $item):
if ($item['subject_id'] == "3"){
$file_data_array[] = array(
"y" => $item['result'],
////Need condition here///////////////////////////////
"color" => '#FFF'
);
}
endforeach;
So I need a condition like
if ($item['confirmed'] == 1) {
"color" => '#FFF'
} else {
"color" => '#000'
}
So, since we cannot put an if inside an array, how can I do my condition?
Try and use the ternary if:
foreach ($score as $item):
if($item['subject_id'] == "3"){
$file_data_array[] = array(
"y" => $item['result'],
"color" => ($item['confirmed'] == 1 ? '#FFF': '#000')
);
endforeach;
"color" => ($item['confirmed']==1 ? "#FFF" : "#000")
foreach ($score as $item):
if($item['subject_id'] == "3"){
if($item['confirmed'] == 1) {
$color = '#FFF';
} else {
$color = '#000';
}
$file_data_array[] = array(
"y" => $item['result'],
"color" => $color);
endforeach;
<?php
$login_detail=array(0=>array("sumit","8101"),1=>array("ashwani","9526"),2=>array("parmod","2592"),3=>array("jitendra","5792"),4=>array("umesh","5555"));
foreach($login_detail as $value)
{
foreach($value as $value2 )
{
echo $value2." ";
}
echo "<br>";
}
$username=$_POST['txtusername'];
$password=$_POST['txtpassword'];
if($username==$login_detail && $password==$value)
{
header("location: dashbord.php");
}
else
{
header("location: loginexample.php?msg=user name or password is wrong");
}
Ok, i tested what follows and i'll just let you know what i discovered:
echo ('-1' < 0) ? 'true' : 'false'; // will echo "true"
echo ('1' > 0) ? 'true' : 'false'; // will echo "true"
# Notice that '-1' and '1' are strings
Now let's take an array, coming from the database after filtering all the result in order to get only rows with UID = 1.
$this->a = array(
[0] => array(
'UID' => '1',
'PID' => '91',
'Amount' => '-1'
),
[1] => array(
'UID' => '1',
'PID' => '92',
'Amount' => '1'
),
[2] => array(
'UID' => '1',
'PID' => '93',
'Amount' => '1'
)
);
Now i want to create a function posAmount($PID) that returns true if 'Amount' > 0 or false if 'Amount' < 0. (Notice: Amount = 0 is something i don't really care). Also i'd like to write as similar function called negAmount($PID) that returns the exactely opposite of the first. I'd like, now, to introduce you to my twin functions:
public function posAmount($pid)
{
foreach ($this->a as $a)
{
if (count($this->a) == 0) { return false; }
return ($a['PID'] == $pid and $a['Amount'] > 0) ? true : false;
}
}
public function negAmount($pid)
{
foreach ($this->a as $a)
{
if (count($this->a) == 0) { return false; }
return ($a['PID'] == $pid and $a['Amount'] < 0) ? true : false;
}
}
The cool fact is that, regarding the first array (which, i checked with var_dump() keeps its nature trough the entire script):
$istance->negAmount(91); // Returns true, as expected
$istance->posAmount(92); // Returns false, as NOT expected.
# Why do God wants me to get mad?
The problem is that you are always returning on the first iteration of the foreach loop. You should rewrite the functions like this:
public function negAmount($pid) {
if (count($this->a) == 0) { return false; }
foreach ($this->a as $a) {
if ($a['PID'] == $pid) {
if ($a['Amount'] < 0) {
return true;
}
}
}
return false;
}
public function posAmount($pid) {
if (count($this->a) == 0) { return false; }
foreach ($this->a as $a) {
if ($a['PID'] == $pid) {
if ($a['Amount'] > 0) {
return true;
}
}
}
return false;
}
May just be a typo in your demo code, but posAmount method is looping $this->a, whereas the other is looping $this->votes - OP corrected
You've got some odd things in your code. Why are you checking the count of $this->a from within a foreach loop? It would make more sense to check the count before you start looping.
Also, you've got some logic errors in your comparison. You're only comparing the first iteration through the loop... it will either return true or false for the first index of the array and never even look at the others. You'll want to match the PID in the loop before you compare - and return - any thing. Like so:
public function posAmount($pid)
{
if (count($this->a) == 0) { return false; }
foreach ($this->votes as $a) {
if ($a['PID'] == $pid)
return $a['Amount'] > 0 ? true : false;
}
return false;
}
public function posAmount($pid)
{
if (count($this->a) == 0) { return false; }
foreach ($this->votes as $a) {
if ($a['PID'] == $pid)
return $a['Amount'] < 0 ? true : false;
}
return false;
}
The problem is you're trying to compare a string to an int without trying to convert it. Change $a['Amount'] to (int)$a['Amount'] and see what happens.
So here you iterate $this->a:
public function posAmount($pid)
{
foreach ($this->a as $a)
But here $this->votes:
public function posAmount($pid)
{
foreach ($this->a as $a)
Typo or what...