I made an iterative loop and created two matrices and I want when I find a specific name I put the corresponding value from the other row in the J variable but I gave me the wrong result which is the number 8 where the number was supposed to appear 7
// my code:
<?php
include 'DB.php';
$db=DB::getInstance();
//$posts = $db->table('posts')->get();
//echo json_encode($posts);
//$users = $db->table("posts")->Qget();
$rows = $db->table('posts')->get();
$filter_value1 = [];
$filter_value2 = [];
$i=0;
$j=0;
foreach($rows as $row){
$filter_value1[]=$row->name;
$filter_value2[]=$row->user_id;
if($filter_value1[$i]="gmal"){
$j= $filter_value2[$i];
}
// echo "$row->name <br>";
$i++;
}
echo($j);
= : This is an assignment operator in any Language suppose we want to assign some value to a variable we will use (equal to) = sign. It does not return anything. e.g.
$name= "gmal";
== : This is a comparison operator. If we want to compare two values or values hold by variables we should use ==. This operator returns True /False bases on comparison e.g.
if("22" == 22) it will return true
=== : Checks the values as well as the type of operands.
if("22" === 22) it will return false
if($name == "gmal"){
echo "Name is : {$name}";
}
so in your code change the following line
if($filter_value1[$i]="gmal")
to
if($filter_value1[$i] == "gmal")
Related
I have assigned a condition into a variable. Then I tried to put that variable as a parameter of a if statement. But the code is not working. Please check my code:
$a = 8;
$final_str = '$a == 10';
if($final_str) {
echo 'Output 1';
} else {
echo 'Output 2';
}
The desired output should be Output 2. But it is not working. I always see Output 1. Please help me in this case.
Thanks in advance!
As per your request, the real problem here is this line of code:
$final_str = '$a == 10';
Although you have said that you cannot change the first two lines of code as it is what you have intended, I think that what you have intended and the result of this are two different things.
You see, you are defining '$a == 10' which is interpreted literally as a string value.
So you are trying to do something like:
if ('some string') ...
The result of this is true because a string that is not empty is a truthy value.
I think your intention however, was to test if the variable $a is equal to the integer value of 10?
In which case you actually need to do:
$final_str = $a == 10;
The result of this can be true or false depending on whether the variable $a is equal to 10 or not, that way your if condition will reflect the desired result?
EDIT:
If however you are trying to create some PHP code dynamically within your string you'd need to run it through eval and here is more information relating to the usage.
EDIT 2:
I would rather try to re-factor this into something more like:
$thisPage = 8;
$truthyPages = array(10,20);
if (in_array($thisPage,$truthyPages)) {
echo 'positive output';
} else {
echo 'negative output';
}
Or maybe even:
$a = 8;
// Step 1
$final_result = $final_result || $a == 10;
// Step 2
$final_result = $final_result || $a == 20;
if ($final_result) {
echo 'success';
} else {
echo 'failure';
}
Is there a shorthand way of writing the code below?
if (($tstat=='no_prices')&&($l1stat=='no_prices')&&($l2stat=='no_prices')&&($l3stat=='no_prices'))
{
//do something
}
I tried using the below code,but it did something when one of the variables was not equal to 'no_prices'.
if (($tstat && $l1stat && $l2stat && $l3stat)=='no_prices')
{
//do something
}
To check that the strings weren't causing problems I tried substituting 0 for 'no_prices' and 1 for other values, but the result was the same.
array_flip is several times faster than array_unique:
function all_equal($arr, $value) {
return array_keys(array_flip($arr)) == array($value);
}
$arr = array($tstat, $l1stat, $l2stat, $l3stat);
echo all_equal($arr, 'no_prices');
A quick profile for the answers given thus far, for 1000 iterations on array length 1000:
array_flip: 0.07321620 seconds
array_unique: 0.32569408 seconds
foreach: 0.15136194 seconds
array_filter: 0.41404295 seconds
The code used to profile is here: http://codepad.org/szgNfWHe
Note: As #cypherabe rightly points out, array_flip does not overtake array_unique until the array has at least 5 elements, and does not overtake foreach until the array has at least 10 elements.
Unless I'm mistaken, there's no native way of doing this. If this is something that you have to check for often, try using a custom function for it, e.g.:
function allEquals($chkstr, $vals) {
if (!is_array($vals)) { die('allEquals() $vals not an array'); }
foreach ($vals AS $v) {
if ($chkstr != $v) { return false; }
}
return true;
}
My first idea would go into PHP's Array API:
// $tstadt, $l1stat, … are all "no_prices"
$isAllNoPrice = array_unique(array($tstat, $l1stat, …)) == array("no_prices"));
if ($isAllNoPrice) {
// …
}
Documentation is mandatory otherwise nobody (including yourself) will understand the code.
If efficiency might be a concern others pointed out that array_unique() seems to be slow. Using the keys of the hash table would be a next approach:
// $tstadt, $l1stat, … are all "no_prices"
$varsMap = array(
$tstat => null,
$l1stat => null,
// …
);
if (array_keys($varsMap) == array("no_prices")) {
// …
}
But now the wall of code is growing. PHP offers one operator which nearly does what you want and is chainable: &
$v1 = "no_prices";
$v2 = "no_prices";
$v3 = "no_prices";
var_dump(($v1 & $v2 & $v3) == "no_prices"); // bool(true)
$v3 = "prices";
var_dump(($v1 & $v2 & $v3) == "no_prices"); // bool(false)
I said it nearly does what you want: There are cases in which you will have false positives:
$v1 = 1;
$v2 = 1;
$v3 = 3;
var_dump(($v1 & $v2 & $v3) == 1); // bool(true)
For Strings it seems to cut the bitmask to the shortest string:
$v1 = "abcd";
$v2 = "ab";
$v3 = "abc";
var_dump($v1 & $v2 & $v3); // "ab"
var_dump(($v1 & $v2 & $v3) == "ab"); // bool(true)
So I don't recommend this as a general purpose solution. Only if you know (=unit tested) that your values are in a set where no combination never results to a false positive (e.g. {"dog", "cat", "horse"}) you might consider this solution. I gave it a second thought and must say don't use that at all. Imagine how your colleagues will love you for searching a bug introduced by that method.
In your case you can do:
if (count(array_unique($tstat, $l1stat, $l2stat, $l3stat)) == 1 //Check if all share the same value (i.e., number of unique values is 1
&& $tstat == 'no_prices')) //If everything is the same and $stat == 'no_prices', then everything is 'no_prices'
{
}
<?php
$tstat = $l1stat = $l2stat = $l3stat = 'no_prices';
$testVars = array($tstat,$l1stat,$l2stat,$l3stat);
if(count(array_filter($testVars, function($x) { return $x === 'no_prices'; })) == count($testVars))
{
print("Correct");
}
Use array_filter with a anonymous callback, and check if its length is greater is equal to original array i.e. all conditions passed,
or if length is greater than zero i.e. any one condition passed
No, this code won't work:
if (($tstat&&$l1stat&&$l2stat&&$l3stat)=='no_prices')
{
//do something
}
Why? Because condition in parentheses, will check result itself - You are comparing boolean to string. So in pseudo-code, thats what your code looks like:
if ( ($tstat is true, $l1stat is true, $l2stat is true, $l3stat is true) == 'no_prices' )
^ whole thing returns true ^ ^ true ^
If you wan't to achieve this, you can use count() and array_unique():
if ($tstat == 'no_prices' && count(array_unique(array($tstat, $l1stat, $l2stat, $l3stat))) == 1)
try this:
$arr = array($tstat,$l1stat,...); //make an array
$arr =array_unique($arr);//unique this array
if(count($arr) == 1 && $arr[0] = 'no_prices'){ // check if only one array element have with same value
echo "got it";
}
demo example
The answer is "no". There's no shorthand to the given condition that will make your code more readable, which should be your top priority. You can improve it though:
define('MYAPP_NO_PRICES', 'no_prices');
if ($tstat === MYAPP_NO_PRICES
&& $l1stat === MYAPP_NO_PRICES
&& $l2stat === MYAPP_NO_PRICES
&& $l3stat === MYAPP_NO_PRICES) {
// do something
}
Having all these vars to check individually is a code smell; you might want to rethink this design so you never have to do this.
echo "<h2 style='margin:0; padding:0;'>Recent Comments</h2>";
if ($sth7->rowCount()) {
while($row7 = $sth7->fetch(PDO::FETCH_ASSOC)) {
echo "<div class='comment'>{$row7['usr']} said";
}
}
else($sth7->rowCount() = 0)
echo "User";
Can't use method return value in write context
Why doesnt that rowcount() = 0 logic work?
= is the assignment operator in PHP.
You're basically trying to assign 0 to $sth7->rowCount().
Perhaps you mean $sth7->rowCount() == 0?
Also, you really don't need the if else if. It could be just an if else:
if($sth7->rowCount()) {
} else {
}
rowCount() returns an integer, and any integer except for 0 will cast to true.
Try rowcount() == 0 to compare with 0, your code (rowcount() = 0) tries to assign 0. Also, it's may be useful to put constant on the left side while comparing : (0 == rowcount()) to make such errors easier to detect.
else doesn't take any logic, it just runs if it's assosciated if (and any elseifs) didn't evaluate true.
Also, = is an assignment operator - read it as "becomes equal to"
$var = 1; // Var becomes equal to 1
== is an equality operator, it tests if two expressions are equal
$var == 1 // Var is equal to 1
You probably want
else if ($sth7->rowCount() == 0)
echo "User";
i'm practicing php at nowadays. i have one question.
i see one = on some while loops. often on mysql queries. so what does it stands for?
two == means equal. but single = ? can you tell me the logic behind this?
Single = means "assignment". An assignment always assigns to a variable and returns the result. So, for example:
while($row = mysql_fetch_array($results)) {
// ...
}
While mysql_fetch_array($results) returns a valid array, it loops. When it returns null (meaning that's the end of the results) the loop exits.
while ($row = mysql_fetch_row($query))
{
//do stuff
}
This keeps querying the result handle until a NULL value (end of result) is found. $row then contains the row fetched from the call so it can be used for processing.
It is also "shorthand" for checking for a NULL result:
while (($row = mysql_fetch_row($query)) != null)
{
//do stuff
}
It can also replace a for loop:
for ($i = 0; $i < mysql_num_rows($query); $i++)
{
//do stuff
}
All are equivalent.
single = is for assignment
$a = 9;
== is for comparison
if($a == 9) echo 'hello';
http://www.w3schools.com/PHP/php_operators.asp
That's the assignment operator.
While the current value of 'x' can be successfully assigned to variable 'y', continue on.
Here is an alternative:
$row = mysql_fetch_assoc($thing);
while (isset($row)) {
// do stuff
$row = mysql_fetch_assoc($thing);
}
You can see that it's a bit less typing (and the code is probably more efficient) here:
while (($row = mysql_fetch_assoc($thing)) != null) {
// do stuff
}
I have the following code
while($row = $usafisRSP->fetch_assoc())
{
$hidden_keys = array('Applicantid', 'unique_num', 'regs_time' ....);
$hidden_fields = array_intersect_key($row, array_fill_keys($hidden_keys, NULL));
$hidden_values = array();
foreach ($hidden_fields as $key => $value) {
// fill the values array using the values from fields array
$hidden_values[$value] = "$key = ".base64_decode($value)."";
if(base64_decode($value)== 0)
{
$hidden_values[$value] = "";
}
echo $hidden_values[$value];
The question is about "if($hidden_values[$value] == 0)" ... Basically I want to do not display/echo the $hidden_values[$value] if it's value of $value is 0. Sometimes $value is 0 or some words like (23 avenue).
I think you ran into three catches with PHP type comparisons and equalities:
Any string not beginning with a number will always loosely equal 0. So basically, if(base64_decode($value)== 0) will likely always resolve to true, even if decoded $value is "Adam".
Return value of base64_decode is a string, so if 0 is the result, it will be string 0, not integer 0. This means if(base64_decode($value) === 0) wouldn't even work if decoded $value is "0". Another catch is base64_decode may return false on errors, again failing this strict equality check.
A non-empty string (other than "0") will always loosely equal true. So this is the only comparison you really need for your case.
I think this is what you want, replacing the last 5 lines...
if(base64_decode($value)) echo $hidden_values[$value];
else $hidden_values[$value] = "";
} // closing your for loop
Is this what you're looking for?
foreach( $hidden_values as $value ) {
if( $value !== 0 ) {
echo $value;
}
}