In some cases the below XPath does not have any value.
$place = extractNodeValue('div[contains(#class, "fn")]/a', $xPath);
I tried to find if it does not contain with the empty function and $place='' without luck.
Is there any way to make this possible?
Using var_dump I get NULL.
The definition of the function extractNodeValue() is missing in your code-example. Therefore this can not be really answered, that is like a black box.
According to the var_dump in your question you need to compare if $place is identical to NULL, that is $place === NULL or is_null($place).
Example (verbose):
$place = extractNodeValue('div[contains(#class, "fn")]/a', $xPath);
$hasValue = $place !== NULL;
if ($hasValue)
{
# do something with $place
}
If you're referring to your extractNodeValue() function from your question xPath or operator two compute more than two? currently it may return:
NULL - if your XPath query doesn't match anything;
Empty string ('') - if the XPath matches some nodes, but the attribute you provided or the node value is indeed an empty string, since both DOMElement::getAttribute and DOMNode::getValue return strings.
Anyhow, PHP empty considers both scenarios as empty, so without an example to see how you're using it, there's no way to tell where you ran out of luck.
If you don't want to distinguish the 2 cases above, my advise would be to standardize the function's output by changing it to:
function extractNodeValue($query, $xPath, $attribute = null) {
$node = $xPath->query("//{$query}")->item(0);
if (!$node) {
return '';
}
return $attribute ? $node->getAttribute($attribute) : $node->nodeValue;
}
With this a simple validation as follow should work:
$place = extractNodeValue('div[contains(#class, "fn")]/a', $xPath);
if (!empty($place)) {
// do something
} else {
// do something else
}
Related
Being new to programming, I am trying to sharpen my skills using the LeetCode problems. I started doing the Longest Common Prefix problem and came up to a problem where the $temp_var doesn't get assigned to a return value of reduceOneAndCheck method.
On the second iteration, the **reduceOneAndCheck **find the first common prefix and gets to return statement, but the $temp_var never gets assigned to that value.
So, my question is, if someone understands why it doesn't get assigned, why it happens? Where did it go wrong? Tried checking for any similar problem already, but didn't find anything, sorry if I missed some solution, being a newbie :)
`
class Solution {
/**
* #param String[] $strs
* #return String
*/
function longestCommonPrefix($strs) {
$temp_var;
foreach ($strs as $value) {
if($temp_var === null || $temp_var === "") {
$temp_var = $value;
}
$temp_var = $this->reduceOneAndCheck($temp_var, $value);
}
return $temp_var;
}
function reduceOneAndCheck(string &$temp_var, string $value) {
if($temp_var == $value) {
return $temp_var;
} else {
$str_tmp = substr($temp_var, 0, -1);
$this->reduceOneAndCheck($str_tmp, $value);
}
}
}
`
These are the values that are used to test the solution:
Input: strs = ["flower","flow","flight"]
Output: "fl"
My code outputs just flight value, because as I came to understand when it comes to second iteration and check for common prefix between "flower" and "flow" and finding it is "flow" the $temp_var never gets assigned the "flow" value, instead it is empty and then the if in longestCommonPrefix method just assigns it to "flight" and that gets returned.
But I do not understand why it never gets assigned to "flow".
Many thanks for any help! :)
Your error is at line:
$temp_var;
just below
function longestCommonPrefix($strs) {.
You are checking if $temp_var is equal to "" or null but it has no initial value.
Solution: Change the said line with error to
$temp_var = "";
I am not at all expert in php. Working in a drupal view, I need to conditionally format several fields. To get sanitized node values I can use:
$thsField = field_get_items('node', $node, 'field_first');
$output = field_view_value('node', $node, 'field_first',$thsField[0]);
but since I have to do this numerous times I wanted to use a function which I can pass the field names into. Something like
$node = node_load($data->nid);
function getValue($var)
{
$thsfield = field_get_items('node', $node, $var);
$fieldvalue = field_view_value('node', $node, $var,$thsfield[0]);
return $fieldvalue;
}
But am having no luck. Is there some way special way to have the string value of $var be understood in this usage, or am I doing something fundamentally wrong according to php? (edit: added node def - which WAS already present in my test. The $node and $data values are definitely populated and in scope)
I think there may be something I'm not understanding about php scope (or Drupal access permissions?). If I do this:
function getValue()
{
$node = node_load($data->nid);
$thsfield = field_get_items('node', $node, 'field_first_author');
$thsvalue = field_view_value('node', $node, 'field_first_author',$thsfield[0]);
print render($thsvalue);
}
I get this error: "ResponseText: EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids()"
If I comment out the function name and brackets, it prints the value as expected.
This was a scope issue, no problem with php interpreting variables. Changing the fn to:
function getValue($var,$node)
{
$thsfield = field_get_items('node', $node, $var);
$fieldvalue = field_view_value('node', $node, $var,$thsfield[0]);
return $fieldvalue;
}
worked!
I have found there to be multiple ways to check whether a function has correctly returned a value to the variable, for example:
Example I
$somevariable = '';
$somevariable = get_somevariable();
if ($somevariable)
{
// Do something because $somevariable is definitely not null or empty!
}
Example II
$somevariable = '';
$somevariable = get_somevariable();
if ($somevariable <> '')
{
// Do something because $somevariable is definitely not null or empty!
}
My question: what is the best practice for checking whether a variable is correct or not? Could it be different for different types of objects? For instance, if you are expecting $somevariable to be a number, would checking if it is an empty string help/post issues? What is you were to set $somevariable = 0; as its initial value?
I come from the strongly-typed world of C# so I am still trying to wrap my head around all of this.
William
It depends what you are looking for.
Check that the Variable is set:
if (isset($var))
{
echo "Var is set";
}
Checking for a number:
if (is_int($var))
{
echo "Var is a number";
}
Checking for a string:
if (is_string($var))
{
echo "var is a string";
}
Check if var contains a decimal place:
if (is_float($var))
{
echo "Var is float";
}
if you are wanting to check that the variable is not a certain type, Add: ! an exclamation mark. Example:
if (!isset($var)) // If variable is not set
{
echo "Var Is Not Set";
}
References:
http://www.php.net/manual/en/function.is-int.php
http://www.php.net/manual/en/function.is-string.php
http://www.php.net/manual/en/function.is-float.php
http://www.php.net/manual/en/function.isset.php
There is no definite answer since it depends on what the function is supposed to return, if properly documented.
For example, if the function fails by returning null, you can check using if (!is_null($retval)).
If the function fails by returning FALSE, use if ($retval !== FALSE).
If the function fails by not returning an integer value, if (is_int($retval)).
If the function fails by returning an empty string, you can use if (!empty($retval)).
and so on...
It depends on what your function may return. This kind of goes back to how to best structure functions. You should learn the PHP truth tables once and apply them. All the following things as considered falsey:
'' (empty string)
0
0.0
'0'
null
false
array() (empty array)
Everything else is truthy. If your function returns one of the above as "failed" return code and anything else as success, the most idiomatic check is:
if (!$value)
If the function may return both 0 and false (like strpos does, for example), you need to apply a more rigorous check:
if (strpos('foo', 'bar') !== false)
I'd always go with the shortest, most readable version that is not prone to false positives, which is typically if ($var)/if (!$var).
If you want to check whether is a number or not, you should make use of filter functions.
For example:
if (!filter_var($_GET['num'], FILTER_VALIDATE_INT)){
//not a number
}
I have an array, inside an array. I'd like to search the values in that nestled array.
Currently I'm trying:
foreach($retval as $k=>$v){
if (is_array($v)){
$search = array_search($group_name,$v);
}
}
if($search == FALSE) {
// Nothing was found
} else {
// results found
}
Once this has been done, I simply want to perform an action depending on whether a result was found or not in the search.
How do you do this?
You need to change $search = array_search($group_name,$v); to:
$search = false;
foreach($retval as $k=>$v){
if(array_search($group_name,$v)){
$search = true;
}
}
Basically, you only want to assign true to search if you found the value you are looking for. Otherwise you could overwrite search's value with false. For example, say search is in element 0, you set it to true. Then in element 1 the element is not there, you then set search to false.
Furthermore, if you only care about knowing it's there, you could add break; after $search = true; to stop searching the array.
Since PHP is a dynamic language what's the best way of checking to see if a provided field is empty?
I want to ensure that:
null is considered an empty string
a white space only string is considered empty
that "0" is not considered empty
This is what I've got so far:
$question = trim($_POST['question']);
if ("" === "$question") {
// Handle error here
}
There must be a simpler way of doing this?
// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
return ($str === null || trim($str) === '');
}
Old post but someone might need it as I did ;)
if (strlen($str) == 0){
do what ever
}
replace $str with your variable.
NULL and "" both return 0 when using strlen.
Use PHP's empty() function. The following things are considered to be empty
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
For more details check empty function
I'll humbly accept if I'm wrong, but I tested on my own end and found that the following works for testing both string(0) "" and NULL valued variables:
if ( $question ) {
// Handle success here
}
Which could also be reversed to test for success as such:
if ( !$question ) {
// Handle error here
}
Beware false negatives from the trim() function — it performs a cast-to-string before trimming, and thus will return e.g. "Array" if you pass it an empty array. That may not be an issue, depending on how you process your data, but with the code you supply, a field named question[] could be supplied in the POST data and appear to be a non-empty string. Instead, I would suggest:
$question = $_POST['question'];
if (!is_string || ($question = trim($question))) {
// Handle error here
}
// If $question was a string, it will have been trimmed by this point
There is no better way but since it's an operation you usually do quite often, you'd better automatize the process.
Most frameworks offer a way to make arguments parsing an easy task. You can build you own object for that. Quick and dirty example :
class Request
{
// This is the spirit but you may want to make that cleaner :-)
function get($key, $default=null, $from=null)
{
if ($from) :
if (isset(${'_'.$from}[$key]));
return sanitize(${'_'.strtoupper($from)}[$key]); // didn't test that but it should work
else
if isset($_REQUEST[$key])
return sanitize($_REQUEST[$key]);
return $default;
}
// basics. Enforce it with filters according to your needs
function sanitize($data)
{
return addslashes(trim($data));
}
// your rules here
function isEmptyString($data)
{
return (trim($data) === "" or $data === null);
}
function exists($key) {}
function setFlash($name, $value) {}
[...]
}
$request = new Request();
$question= $request->get('question', '', 'post');
print $request->isEmptyString($question);
Symfony use that kind of sugar massively.
But you are talking about more than that, with your "// Handle error here
". You are mixing 2 jobs : getting the data and processing it. This is not the same at all.
There are other mechanisms you can use to validate data. Again, frameworks can show you best pratices.
Create objects that represent the data of your form, then attach processses and fall back to it. It sounds far more work that hacking a quick PHP script (and it is the first time), but it's reusable, flexible, and much less error prone since form validation with usual PHP tends to quickly become spaguetti code.
This one checks arrays and strings:
function is_set($val) {
if(is_array($val)) return !empty($val);
return strlen(trim($val)) ? true : false;
}
to be more robust (tabulation, return…), I define:
function is_not_empty_string($str) {
if (is_string($str) && trim($str, " \t\n\r\0") !== '')
return true;
else
return false;
}
// code to test
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
var_export($value);
if (is_not_empty_string($value))
print(" is a none empty string!\n");
else
print(" is not a string or is an empty string\n");
}
sources:
https://www.php.net/manual/en/function.is-string.php
https://www.php.net/manual/en/function.trim.php
When you want to check if a value is provided for a field, that field may be a string , an array, or undifined. So, the following is enough
function isSet($param)
{
return (is_array($param) && count($param)) || trim($param) !== '';
}
use this :
// check for null or empty
if (empty($var)) {
...
}
else {
...
}
empty() used to work for this, but the behavior of empty() has changed several times. As always, the php docs are always the best source for exact behavior and the comments on those pages usually provide a good history of the changes over time. If you want to check for a lack of object properties, a very defensive method at the moment is:
if (is_object($theObject) && (count(get_object_vars($theObject)) > 0)) {