I have a bit of php code that I'm not understanding why it is acting as it is. I have a variable called contactId that I want to test to see if it is empty. However even if it is empty it evaluates to true. Code is below. Thanks in advance.
print "*".$contactId."*<br/>";
if($contactId != '')
{
//queryContact($contactId);
print "Contact Present<br/>";
}
result returned to screen is:
**
Contact Present
If you want to see exactly what your string is, simply use var_dump(), like this, for instance:
var_dump($contactId)
instead of
print "*".$contactId."*<br/>";
Couple of things you can try:
if (!empty($contactId)) {
// I have a contact Id
}
// Or
if (strlen($contactId) > 0) {
// I have a contact id
}
In my experience I have often used the latter of the two solutions because there have been instances where I would expect a variable to have the value of 0, which is valid in some contexts. For example, if I have a drink search site and want to indicate if an ingredient is non-alcoholic I would assign it a value of 0 (i.e. IngredientId = 7, Alcoholic = 0).
Do it with if (isset($contactId)) {}.
You likely want:
if (strlen($contactId))
You'll want to learn the difference between '' and null, and between == and ===. See here: http://php.net/manual/en/language.operators.comparison.php
and here: http://us3.php.net/manual/en/language.types.null.php
In future, use if(!empty($str)) { echo "string is not empty"}.
Related
Learning PHP and I have a question.
How does one obtain an element from an array and determine if it is equal to a static value? I have a return set from a query statement (confirmed the array has all values).
I tried:
<? if($row["rowValue"] == 1) {
}
?>
I was expecting the value to be 1, but it's returning null (as if I'm doing it wrong).
You're pretty much there; something like this should confirm it for you:
echo "<p>Q: Does ".$row["rowValue"]." = 1?</p>";
if($row["rowValue"] == 1) {
echo "<p>A: Yes ".$row["rowValue"]." does equal 1</p>";
} else {
echo "<p>A: No, '".$row["rowValue"]."' does not equal 1</p>";
}
If that's still returning 'No' you could try viewing the whole of the $row array by doing a var dump of the array like so:
var_dump($row);
This will give you detailed output of how the array is built and you should be able to see if you are calling the correct element within the array.
What is returning null?
Try this:
if($row["rowValue"] === 1) { ... }
Make sure there is an element in $row called rowValue.
maybe try:
<? if($row[0]["theNameOfAColumn"] == 1) {
}
?>
Usually databases return rows like row[0], row[1], row[2], etc.
I am not sure what exactly you are doing, but try using array_filp() which will Exchanges all keys with their associated values
than you can do like
if($row["rowValue"] == 1) {
http://in1.php.net/manual/en/function.array-flip.php
If you're pulling it from mysqli_fetch_row then it wants a number, not a column name. If it's being pulled from mysqli_fetch_array then it will accept a column name.
http://php.net/manual/en/mysqli-result.fetch-row.php
http://php.net/manual/en/mysqli-result.fetch-array.php
Hi Guys Hope you can Help:
I am trying to read the xml that is part of a sports scheduling program.
I have Below a Sample of the XML I am reading. So far using Simpmle XML I have been able to read all attributes of a game correctly. However in The example you can see that homescore and awayscore will only show as "" until a score is entered. This is great because I want to put a simple if statement saying if score is null echo "-". This way the viewer knows they are yet to play.
<Fixture Id="404" FixtureName="Round 4" ResourceId="4" PlayingAreaName="Court C" VenueId="2" VenueName="Adelaide Indoor Sports Centre" MapLink="" HomeTeamId="212" HomeTeam="THE SHINERS" HomeTeamScore="29" HomeTeamForfeit="False" AwayTeamId="203" AwayTeam="SANDBAR WARRIORS" AwayTeamScore="8" AwayTeamForfeit="False" Duration="40" Umpires="" CrossLeague="False" DivisionName="Division 1" CalendarColour="FFFF00" ResourceOrder="3" DateTime="13/03/2012 21:20"/>
<Fixture Id="406" FixtureName="Round 4" ResourceId="5" PlayingAreaName="Court D" VenueId="2" VenueName="Adelaide Indoor Sports Centre" MapLink="" HomeTeamId="210" HomeTeam="WE THOUGHT IT WAS A DISCO" HomeTeamScore="" HomeTeamForfeit="False" AwayTeamId="206" AwayTeam="AVERAGE JOE'S" AwayTeamScore="" AwayTeamForfeit="False" Duration="40" Umpires="" CrossLeague="False" DivisionName="" CalendarColour="FFFF00" ResourceOrder="4" DateTime="13/03/2012 21:20"/>
But The "" (empty attribute) always returns zero. Any Tips? I'm relatively new to php
You could use the empty() function.
if (empty($fixture['HomeTeamScore'])) {
echo "-";
}
PHP: empty - Manual
If I understand you correctly, you want to distinguish between "" and "0". Because PHP tries as hard as it can to guess what types you're comparing, statements like $foo == 0 and $foo == '' won't do this, as it will guess that you want to compare numbers, and treat "" as 0.
There are a couple of ways to deal with this:
use the === operator instead of == (or !== instead of !=) (see http://uk3.php.net/manual/en/language.operators.comparison.php)
check the length of the string using strlen to see if it is empty
check the type of the variable using is_int, is_string, etc - this one probably won't work if you've grabbed the values out of SimpleXML, which returns its own types
Since you're using SimpleXML, I would imagine the code would look something like:
if ( (string)$fixture['HomeTeamScore'] === '' )
{
echo '-';
}
else
{
echo (string)$fixture['HomeTeamScore'];
}
i have two time values as give below
$row2[0]=00:40:00;
$row1[5]=14:00:00;
$time=14:33:00
$time=$row[1];
i am combining $row2[0],$row1[5] like below
$secs = strtotime($row2[0])-strtotime("00:00:00");
$result = date("H:i:s",strtotime($row1[5])+$secs);
$result=14:40:00
i use if condition as shown
if($row[1]>$row1[5] && $row[1]<$result)
{
$message=array("status"=>$result);
}
else
{
$message=array("status"=>'');
}
but i get "status"=>"" its not correct
i want to get "status"=>"14:40:00"
please help us for getting correct out put
You don't appear to define $row[1] anywhere, so it is treated as NULL, which as an integer is 0, which cannot be greater than the time you have given in $row1[5].
Try using less ambiguous variable names, it might make it easier to spot problems like this.
Personally I don't see why that if is there at all, just remove it and the else block, leaving just $message = array("status"=>$result);.
is this real oder pseudo code ?
because
$row2[0]=00:40:00;
is not real php code !
$row2[0] = 00:40:00; // $row2[0] would be 0, because you are assigning an integer
$row2[0] = "00:40:00"; // $row2[0] would be "00:40:00", but as a string (!)
i would always work with timestamps btw.
I go with Panique on his answer, I want to add also:
You declared two vars:
$row2[0]=00:40:00;
$row1[5]=14:00:00;
But you called different array elements in the if
if($row[1]>$row1[5] && $row[1]<$result)
Solve this and you should have your code working.
What do the two equal signs mean when not being used to compare?
$saveOrder = $listOrder == 'a.ordering';
I've never seen anything like this in php.... I am looking at the weblinks Joomla 1.7 admin component.
Thanks
It is used for comparing. Except the result of the comparison is assigned to $saveOrder.
The following code:
<?php
list($listOrder1, $listOrder2) = array('a.ordering', 'a.something_else');
$saveOrder1 = $listOrder1 == 'a.ordering';
$saveOrder2 = $listOrder2 == 'a.ordering';
assigns true to the $saveOrder1 variable and false to the $saveOrder2 variable. If you do not believe, check for yourself here.
They are comparing. It's just not wrapped in parenthesis (like a comparison expression with if/while/etc).
$saveOrder will be assigned either true or false (the result of the condition).
I guess it is the same as $saveOrder = ($listOrder == 'a.ordering');
In your statement also the double equal sign(==) used for the comparison purpose only. Actually your statement contains both the 'assignment'(=) and 'comparison'(==) operators which leads to your confusion.
That is equivalent to $saveOrder = ($listOrder == 'a.ordering');, so first compares the $listOrder with 'a.ordering' and assign the result(true or false) to $saveOrder.
Hope this clear you confusion, if not let me know once.
$listOrder1='a.ordering';
$listOrder1='wrong'
$saveOrder1 = $listOrder1 == 'a.ordering';//1
$saveOrder2 = $listOrder2 == 'a.ordering';//
You can see the output when printing the first will be 1 whereas the second will return: (i.e. nothing)
I wanted to allow only specific email domain. Actually I did it. What i wanted to ask why my first code did not work at all.
I am just trying to learn PHP so that the question may seem silly, sorry for that.
Here is my code:
function check_email_address($email) {
$checkmail = print_r (explode("#",$email));
$container = $checkmail[1];
if(strcmp($container, "gmail.com")) {
return true;
}else {
return false;
}
}
Check out the documentation for strcmp() , it will return 0 of the two strings are the same, so that's the check you want to be doing. Also, you're using print_r() when you shouldn't be, as mentioned by the other answerers.
Anyway, here's how I would have done the function - it's much simpler and uses only one line of code:
function check_email_address($email) {
return (strtolower(strstr($email, '#')) == 'gmail.com');
}
It uses the strstr() function and the strtolower() function to get the domain name and change it to lower case, and then it checks if it is gmail.com or not. It then returns the result of that comparison.
It's because you're using print_r. It doesn't do what you seem to expect from it at all. Remove it:
$checkmail = explode("#", $email);
You can find the docs about print_r here:
http://php.net/print_r
Besides that, you can just use the following (it's much shorter):
$parts = explode("#", $email);
return (strcmp($parts[1], "gmail.com") == 0);
The following row doesn't work as you think it does:
$checkmail = print_r (explode("#",$email));
This means that you're trying to assign the return value from print_r() into $checkmail, but it doesn't actually return anything (if you don't supply the second, optional parameter with the value true).
Even then, it would've gotten a string containing the array structure, and your $container would have taken the value r, as it's the second letter in Array.
Bottom line: if your row would've been without the call to print_r(), it would've been working as planned (as long as you made sure to compare the strcmp() versus 0, as it means that the strings are identical).
Edit:
Interesting enough, I just realized that this could be achieved with the use of substr() too:
<?php
//Did we find #gmail.com at the end?
if( strtolower(substr($email, -10)) == '#gmail.com' ) {
//Do something since it's an gmail.com-address
} else {
//Error handling here
}
?>
You want:
if(strcmp($container, "gmail.com")==0)
instead of
if(strcmp($container, "gmail.com"))
Oh! And no inlined print_r() of course.
Even better:
return strcmp($container, "gmail.com")==0;
No need for the print_r; explode returns a list. And in terms of style (at least, my style) no need to assign the Nth element of that list to another variable unless you intend to use it a lot elsewhere. Thus,
$c = explode('#',$mail);
if(strcmp($c[1],'gmail.com') == 0) return true;
return false;