Forum Moderators: coopster
<?php if (isset($my_desc)) {
echo '<h2>'.$my_desc.'</h2>';
}
else if (isset($res_texte)) {
echo '<h2>'.$res_texte["texte"].'</h2>';
}
else {
echo '';
};
?> The trouble is sometimes
$res_texte["texte"] is empty even if $res_texte is set, so I'm getting an empty <h2></h2> in the resulting source code. This is not a huge problem, but it's scruffy. I would like to test what $res_texte["texte"] is, and if it is empty, not echo the <h2></h2> at all. Is this possible, or there a better way of doing this? Many thanks for your help!
The above msg was done in a hurry and I forgot to explain things a bit.
There're lots of examples of the code above, the best is _POST:
I think that you usually do if(isset($_POST['id']) $id = (int)$_POST["id"]; or sth similar
Best wishes!
Michal Cibor
You could check the length of the string with strlen, and if it's less than, say 2, you might assume the array value is empty (which is different from NULL).
$str = strlen($string);
if ($str < 2)
{
// assumed empty
}
else
{
echo '<h2>'.$res_texte["texte"].'</h2>';
}
This adds an extra layer of testing after using isset, but will almost guarantee no empty strings.
It looks like the array value may be set, but is set with an empty string - one or two bytes of nothingness.
Yes, I think this is exactly the problem, which would explain why I've been having issues with just seeing if the value exists. I like tata668's suggestion too, it looks if it could solve the problem. Thanks!
<?php
if (isset [php.net]($my_desc)) {
echo '<h2>'.$my_desc.'</h2>';
} else if (isset [php.net]($res_texte['texte']) && !empty [php.net](trim [php.net]($res_texte['texte'])) {
echo '<h2>'.$res_texte['texte'].'</h2>';
};
?>
<?php
if (isset($my_desc)) {
echo '<h2>'.$my_desc.'</h2>';
} else if (isset($res_texte['texte']) &&!empty(trim($res_texte['texte'])) {
echo '<h2>'.$res_texte['texte'].'</h2>';
};
?>
I personaly don't like the empty() function because of:
empty(0) == true
and
empty(false) == true
When I work with strings I use my own "myEmpty()" function:
function myEmpty($str)
{
if(!isset($str))
{
return true ;
}
else
{
if(is_string($str))
{
return (strcmp($str, "") === 0) ;
}
else
{
return false ;
}
}
}
But I guess if you always use empty() with trim(), it's safe.
Hope this helps..