I am getting an array, and I filter it to get just the text, in the text I am looking for something like "20/" Making sure the 20/ exist then if it does, it will go to another part of the code BUT I can't seem to figure out how to get it recognized if its a 1-9/ to 20/.
if ($spot = strpos($dir[$x]->output, '9/')) {
echo "Valid";
}
else {
gotto2();
}
So, it doesn't ever find it, but if I remove the number, it'll find the "/".
your if condition is all wrong.
try this,
if (false !== strpos($dir[$x]->output, '9/')) {
echo "Valid";
}
your doing assignment to $spot ( single = ) even a double == is not suffencient to check because if the position is 0, you need to check for Boolean false strictly ( or in this case true, but we dont care about the position so valid is 0 to any pos ) and we cant look for boolen true , so we check for anything but boolean false
if this doen't work you will have to post the input string as well.
Related
Here's what I'm running:
echo $checknetworks;
Here's the results of the echo:
Facebook,Twitter,Myspace,Google,Instagram,Pinterest
What I want to do is check to see if the string google is in the results above. I do not want it to be case sensitive because the capitalization changes from time to time.
Basically if google exists in the string, I want to display "FOUND". If it doesn't exist, I want to display "NOT FOUND".
I came across a couple of somewhat similar questions here but none seemed to take capitalization into account.
You need stripos:
stripos — Find the position of the first occurrence of a case-insensitive substring in a string
$checknetworks = "Facebook,Twitter,Myspace,Google,Instagram,Pinterest";
if (stripos($checknetworks, 'Google') === FALSE)
{
echo 'NOT FOUND';
} else
{
echo 'FOUND';
}
Please note that you should compare types as well. I.e. if your string would start with google, stripos will return 0, that would be interpreted as false, unless you make the type comparison with ===
try using strpos:
<?php
$strVar = (string)$myVar;
if (strpos($strVar, "Google")){
echo "Found"
}else{
echo "Not found"
}
?>
EDIT:
You must check if the strpos returns FALSE, and not the position 0.
Use '===':
if (strpos($strVar, "Google") === FALSE){
I've been working on a very basic search engine. It basically operates by checking if the word exists. If it does, it returns the link. I know most of you would suggest to create a database from phpMyAdmin but I don't remember the password to make the mySql_Connect command work.
Anyway here is the code:
<?php
session_start();
$searchInput = $_POST['search'];
var_dump($inputPage1);
var_dump($searchİnput);
$inputPage1 = $_SESSION['pOneText'];
$inputPage2 = isset($_SESSION['pTwoText']) ? $_SESSION['pTwoText'] : "";
$inputPage3 = isset($_SESSION['pThreeText']) ? $_SESSION['pThreeText'] : "";
if (strpos($inputPage1, $searchInput)) {
echo "True";
} else {
echo "False";
}
?>
When I search a word, any word from any page, weather it exists or not, it always returns false. Does anyone know why?
From the PHP documentation:
Warning: This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
So the function returns the integer 0 since $searchInput starts at the first character of $inputPage1. Since it is inside an if condition, that expects a boolean, the integer is then converted to one. When converted to boolean, zero is equal to false so instead the else block is executed.
To fix it, you need to use the !== operator (the not equal equivalent of ===):
if (strpos($inputPage1, $searchInput) !== false) {
//...
Try stripos() to match case insensitive
First print all items in $_POST and $_SESSION using
echo "<pre>";
print_r($_POST);
print_r($_SESSION);
and ensure that the search string really exist in the bigger string .
Also make sure that your are using "false" to compare :
i.e
$pos = strpos($biggerString,$seachString);
if($pos !== false)
{
echo "Not found";
}
I've a variable which contains comma separated strings. This is generated dynamically from the array elements by using implode() function.So sometimes it contains nothing, sometimes it contains 1/2/3/4 strings separated by comma. I want to check whether the stirng Other is present within this comma separated string and if it's present then do the commands written inside if. But I'm facing a issue in which it's never detecting the string "Other" inside the comma separated values though tit's present. Can anyone help me in this regard please?
For your reference following is my code:
$form_data['que_issue'] = implode(",", $request['que_issue']);
if(strpos($form_data['que_issue'],"Other")) {
echo "In If";
die;
if(!$this->mValidator->validate($form_data['que_issue_comment'], "required", "true"))
$this->mValidator->push_error($errors_msgs['que_issue_comment_blank'], 'que_issue_comment');
elseif(!$this->mValidator->validate($form_data['que_issue_comment'], 'maxlength', '100'))
this->mValidator->push_error($errors_msgs['que_issue_comment_length_invalid'], 'que_issue_comment');
} else
echo "In a else";
die;//Its always going in else part only
Thanks in advance.
strpos will return 0 if string match at the begin of the string. But 0 is interpreted as false by PHP.
Always look the documentation and see what is the specific return type/value when the method "fail" and compare against that. In this case
if(strpos($form_data['que_issue'],"Other") !== false)
you should try something like this
if (strpos($form_data['que_issue'],'Other') !== false) {
Ok... right of the batt, let me clear what the question is not about.
it is not about in_array.
Because as the PHP manual clearly explains, the function 'in_array' checks if a value exists in an array. But it does this check based on equality. It does not do as based on partial existence.
For example, if the value I'm looking is 'overflow' and I happened have an array like this
array('cnn','stackoverflow'),
the in_array would come back with a FALSE, telling me that overflow does not exist in the in values of this array, which in a way is TRUE. but also in a way, is FALSE.
To me, the string "overflow" do exists in the string stackoverflow". Therefore, it should have returned TRUE. Of course I cannot argue this point much.
Is there another function ( or an efficient one-liner) in PHP to get me what I want?
i'm looking for a solution something like this
array_filter($ary,'strlen');
which removes the empty lines from the $ary in a very efficient way.
I do not want to go thru the traditional way that is to go thru a foreach and do a comparison between the needle and the haystack using strpos. That solution I already know.
I'm looking for a one liner, like in the (strlen) example
Thx.
No function available in php which satisfy exact requirement of author. Developer has to write some code so you can try below code:
function array_check($arr, $keyword) {
foreach($arr as $index => $string) {
if (strpos($string, $keyword) !== FALSE)
return $index;
}
}
var_dump(array_check(array('cnn','stackoverflow'),'overflow'));
exit;
Lame option: false !== strpos(implode($ary, '|'),'overflow') As long as the separator character (| here) isn't in your search string, this works.
More sophisticated option: count(array_filter( $ary, function($x) { return strpos($x, 'overflow'); } ) );
Edit: Second option full code looks like this:
$ary = array('cnn', 'stackoverflow'); // or whatever your data is
(bool) count(array_filter( $ary, function($x) { return strpos($x, 'overflow'); } ) );
The count() value will be 0 if not found, or positive if a match was found. So, you could use it in an if() statement, return it from a function, or whatever.
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
}