PHP if statement returns same value - php

My code is always returning true when I'm comparing these variables.
What am I doing wrong?
<?php
$postuser = (integer)bp_activity_user_id(); //echos 1int(0)
$posteduser = (integer)bp_activity_comment_user_id(); //echos 3int(0)
if ( $postuser === $posteduser) {
echo 'true';
} else {
echo 'false';
}
?>

You need to use the function that RETURNs the value, not outputs it.
From docs I found for whatever this is,
bp_activity_user_id() X-Ref
Output the activity user ID.
bp_get_activity_user_id() X-Ref
Return the activity user ID.
return: int The activity user ID.
The function you are using echoes the variable, NOT returns it and therefore you can't set a variable with that function. Same for the this function.
bp_activity_comment_user_id() X-Ref
Output the ID of the author of the activity comment currently being displayed.
bp_get_activity_comment_user_id() X-Ref
Return the ID of the author of the activity comment currently being displayed.
return: int|bool $user_id The user_id of the author of the displayed
To use in an assignment, the function has to return a value. That's why your values are always (int)0: the functions you are using have no return value. So, it returns null which is cast to 0.
<?php
$postuser = bp_get_activity_user_id();
$posteduser = bp_get_activity_comment_user_id();
//no need to cast: these functions return integers
if ( $postuser === $posteduser) {
echo 'true';
} else {
echo 'False';

Just use intval and == i think it should work and evaluate it fine
<?php
$postuser = intval(bp_activity_user_id()); //echos 1int(0)
$posteduser = intval(bp_activity_comment_user_id()); //echos 3int(0)
if ( $postuser == $posteduser) {
echo 'true';
} else {
echo 'False';
}
?>

Your prbolems are probably the wrong typecasts:
Change (integer) to (int)
$postuser = (int)bp_activity_user_id(); //echos 1int(0)
$posteduser = (int)bp_activity_comment_user_id();
http://php.net/manual/en/language.types.integer.php

Related

How do you make sure an array is empty in PHP?

Im writing a page in HTML/PHP that connects to a Marina Database(boats,owners etc...) that takes a boat name chosen from a drop down list and then displays all the service that boat has had done on it.
here is my relevant code...
if(isset($_POST['form1'])){//if there was input data submitted
$form1 = $_POST['form1'];
$sql1 = 'select Status from ServiceRequest,MarinaSlip where MarinaSlip.SlipID = ServiceRequest.SlipID and BoatName = "'.$form1.'"';
$form1 = null;
$result1 = $conn->query($sql1);
$test = 0;
while ($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$values1[] = array(
'Status' => $row['Status']
);
$test = 1;
}
echo '<p>Service Done:</p><ol>';
if($test = 1){
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
echo '</ol>';
}else{
echo 'No service Done';
}
the issue im having is that some of the descriptions of sevice are simply Open which i do not want displayed as service done, or there is no service completed at all, which throws undefined variable: values1
how would I stop my script from adding Open to the values1 array and display a message that no work has been completed if values1 is empty?
Try this
$arr = array();
if (empty($arr))
{
echo'empty array';
}
We often use empty($array_name) to check whether it is empty or not
<?php
if(!empty($array_name))
{
//not empty
}
else
{
//empty
}
there is also another way we can double sure about is using count() function
if(count($array_name) > 0)
{
//not empty
}
else
{
//empty
}
?>
To make sure an array is empty you can use count() and empty() both. but count() is slightly slower than empty().count() returns the number of element present in an array.
$arr=array();
if(count($arr)==0){
//your code here
}
try this
if(isset($array_name) && !empty($array_name))
{
//not empty
}
You can try this-
if (empty($somelist)) {
// list is empty.
}
I often use empty($arr) to do it.
Try this instead:
if (!$values1) {
echo "No work has been completed";
} else {
//Do staffs here
}
I think what you need is to check if $values1 exists so try using isset() to do that and there is no need to use the $test var:
if(isset($values1))
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
Or try to define $values1 before the while:
$values1 = array();
then check if it's not empty:
if($values1 != '')
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
All you have to do is get the boolean value of
empty($array). It will return false if the array is empty.
You could use empty($varName) for multiple uses.
For more reference : http://php.net/manual/en/function.empty.php

Why substr() doesn't work correctly with a number that has a leading zero?

I have this script:
function DecryptId($id) {
$first_digit = substr($id, 0,1);
if ( $first_digit == 0 ) {
return 'yes';
} else {
return 'no';
}
}
$id = 014;
echo DecryptId($id);
//=> no
Demo
Why it prints no? I expect it prints yes. Because the value of $id starts with 0. What's wrong?
EDIT: In reality I'm passing $id like this: DecryptId($_POST['au']);. $_POST['au'] is containing a number. Something like these:
23
43552
0153
314
09884
As you see, sometimes that number starts with 0. And I need to pass it as a string. How can I do that?
Because of the leading zero, PHP will be parsing that number as octal. Even if it didn't do this, most languages will strip off the leading zeros (since they don't actually form part of the number). This means that $id will evaluate to 12.
Are you sure you don't want to declare it as a string? ($id = "014")
Your function is working fine the issue is that you are passing a number in your function when you should provide a string. So in the case that your variable type is integer the leading zero will eventually fly away.
You can add something to your function to check the variable type and inform the user.
function DecryptId($id) {
$type = gettype( $id );
if($type!= "string") {
echo "Your variable has type ".$type.". Use a 'string' type variable";
return;
}
$first_digit = substr($id, 0,1);
if ( $first_digit == 0 ) {
return 'yes';
} else {
return 'no';
}
}
$id = 014;
echo DecryptId($id);
echo "\n";
$id = '014';
echo DecryptId($id);
Try the above example in PHP Sandbox
try this
<?php
function DecryptId($id) {
$first_digit = substr($id, 0,1);
if ( $first_digit == 0 ) {
return 'yes';
} else {
return 'no';
}
}
$id = '014';
echo DecryptId($id);
?>

Yii ajax query return nothing

I want to check is null or empty result in my DB, create this query
$query = "SELECT smtp_login FROM tbl_users WHERE id=". $id. " AND (smtp_login IS NULL OR TRIM(smtp_login)='')";
$list = Yii::app()->db->createCommand($query)->query();
foreach($list as $item){
for($i=0;$i<count($item);$i=$i+1)
{
if(is_null($item[$i]) & $item[$i]=='') { echo 'True'; }
else { echo 'False'; }
}
}
When item is null all is ok, getting True value, but when it isn't returned just empty popup not False.
Use or(||) instead of and(&)
if(is_null($item[$i]) || $item[$i]=='') { echo 'True'; }
Use queryAll() instead of query(). query() returns a single record, but queryAll() - all data matching criteria.

PHP return value from class function not working

I am having problem fetching return value returned by a class function in PHP. Does returning values works exactly the way it works in other languages- C, C++, Java or there is something new to it.
This is my Class:
class M_UserMaster
{
private $_db = null;
function __construct($db)
{
$this->_db = $db;
}
function checkUserExists($mobNum)
{
$userExists = false;
$sql = "SELECT STATEMENT HERE";
$stmnt = $this->_db->prepare($sql);
$stmnt->execute();
$numRows = $stmnt->rowCount();
echo '<br><br>Num Rows: ' . $numRows . '<br>***';
$userExists = ($numRows > 0) ? true : false;
return $userExists;
}
}
The echo statement returns 0. But the function returns nothing.
From another file I am calling it like this:
$m_userMaster = new M_UserMaster($db);
$userExists = $m_userMaster->checkUserExists('0000000000');
echo '<br><br>User Exists: ' . $userExists;
This is what is printed
User Exists:
If you do
$x = true;
echo $x;
You will get output 1
But with
$x = false;
echo $x;
You will get empty string as output
You will need to do something like this:
echo '<br><br>User Exists: ' . ($userExists ? 'yes' : 'no');
Or change return value of your function from true / false to 1 / 0. That will behave similar way, but output will be correct.
You are trying to echo a literal boolean value. PHP prints such values as empty strings. You want to do something like this, instead:
echo '<br><br>User Exists: ' . ($userExists ? 'true' : 'false');
This will echo the first part no matter what. It then checks whether $userExists is true. If so, it prints true; otherwise, it prints false.
Try like
$userExists = ($numRows > 0) ? 'true' : 'false';
As per your code,if the $numRows is greater than 0 then it will return 1 and if the $numRows is 0 then it will return empty because it become false.For clear understand
echo true; // Return 1
echo false; // Return empty

Check if the fetched array is empty or not PHP?

I am trying to check if the mysql_fetch_array() function returns an empty array or not. But my code doesn't seem to work. Here I want to ensure that if the array is empty I want to display under construction message.
Code :
$queryContents= queryMembers();
$exeQuery = mysql_query($queryContents);
while($fetchSet = mysql_fetch_array($exeQuery)) {
if(count($fetchSet) == 0) {
echo "This Page is Under Construction";
}else{
// something else to display the content
}
}
How do I check to acheive such feature ?
use mysql_num_rows to count number of rows. try this.
$exeQuery = mysql_query($queryContents);
if(mysql_num_rows($exeQuery)== 0){
echo "This Page is Under Construction";
}
else{
while($fetchSet = mysql_fetch_array($exeQuery)) {
// something else to display the content
}
}
You really should be using mysql_num_rows http://us2.php.net/manual/en/function.mysql-num-rows.php
However, on a side note, you should use php empty() instead. http://us2.php.net/empty
When you use mysql_fetch_array(), it returns the rows from the data
set one by one as you use the while loop.
If there will be no record, while loop wont execute. In this case, declare a boolean variable and make it true if it enters the while loop. Like:
$queryContents= queryMembers();
$exeQuery = mysql_query($queryContents);
$recordExists = 0;
while($fetchSet = mysql_fetch_array($exeQuery)) {
if($recordExists == 0 )
$recordExists = 1;
// something else to display the content
}
if($recordExists == 0 ){
echo "This Page is Under Construction";
}
Hope this works!
You can do it this way:
while($r[]=mysql_fetch_array($sql));
// now $r has all the results
if(empty($r)){
// do something
}
source: php doc
Your code inside the while loop never runs if there are no results. mysql_fetch_array returns null/false if there are no more results. What you need yo do is check with mysql_num_rows first, before the while.
$queryContents= queryMembers();
$exeQuery = mysql_query($queryContents);
if(mysql_num_rows ($exeQuery) == 0) {
echo "This Page is Under Construction";
}
while($fetchSet = mysql_fetch_array($exeQuery)) {
// something else to display the content
}
Try this
if(empty($fetchSet)
{
echo "This Page is Under Construction";
}
else
{
// something else to display the content
}

Categories