Is there anything wrong with the strpos implementation in below case? - php

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) {

Related

How to check if string exists in variable output?

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){

isset() returns true from a string variable accessed as an array with any key

I face a problem like this:
$area="Dhaka";
isset($area); //returns true which is OK
isset($area['division']); //returns true why?
// actually, any array key of area returns true
isset($area['ANY_KEY']);//this is my question 1
isset($area['division']['zilla');//now it returns false.
//as I know it should returns false but why previous one was true.
Now if I do this:
$area['division'] = "Dhaka";
isset($area); // returns true which is OK
isset($area['division']); // returns true it's also OK
isset($area['ANY_KEY']); // returns false. I also expect this
isset($area['division']['ANY_KEY']); // returns true why? question #2
Basically both of my questions are the same.
Can anyone explain this?
As with every programming language in existence, a string is stored as an array of characters.
If I did:
$area = "Dhaka";
echo $area[0];
It would return D.
I could also echo the whole string by doing:
echo $area[0].$area[1].$area[2].$area[3].$area[4];
PHP will also type juggle a string into 0 when passed in a manner that accepts only integers.
So by doing:
echo $area['division'];
You would essentially be doing:
echo $area[0];
and again, getting D.
That's why isset($area['division']) returns a true value.
Why doesn't $area['foo']['bar'] (aka $area[0][0]) work? Because $area is only a single-dimension array.
The best approach to handle this problem when you're working with a variable that could either be a string or an array is to test with is_array() before trying to treat your variable as an array:
is_array($area) && isset($area['division'])
PHP lets you treat a string as an array:
$foo = 'bar';
echo $foo[1]; // outputs 'a'
So
$area['division']
will be parsed/executed as
$area[0];
(the keys cannot be strings, since it's not REALLY an array, so PHP type-converts your division string by its convert-to-int rules, and gives 0), and evaluate to the letter D in Dhaka, which is obviously set.
Okay, here's a solution rather than explaining why isset isn't going to work properly.
You want to check if an array element is set based on it's index string. Here's how I might do it:
function isset_by_strkey($KeyStr,$Ar)
{
if(array_key_exists($KeyStr,$Ar))
{
if(strlen($Ar[$KeyStr]) > 0 || is_numeric($Ar[$KeyStr] !== FALSE)
{
return TRUE;
}
return FALSE;
}
}
isset_by_strkey('ANY_KEY',$area); // will return false if ANY_KEY is not set in $area array and true if it is.
The best way to access a linear array in php is
// string treated as an linear array
$string= "roni" ;
echo $string{0} . $string{1} . $string{2} . $string{3};
// output = roni
It is expected behaviour.
PHP Documentation covers this
You can try empty() instead.
If it is returning true for keys that do not exist there's nothing you can do; however, you can make sure that it doesn't have a negative effect on your code. Just use array_key_exists() and then perform isset() on the array element.
Edit: In fact, using array_key_exists() you shouldn't even need isset if it is misbehaving just use something like strlen() or check the value type if array_key_exists returns true.
The point is, rather than just saying isset($Ar['something']) do:
if(array_key_exists('something',$Ar) )
and if necessary check the value length or type. If you need to check the array exists before that of course use isset() or is_array() on just the array itself.

PHP Strpos can't find first character?

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.

PHP: check if a value exists in array ( not as equal but as Part of )

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.

Why doesn't my code to test an email address against a specific domain work?

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;

Categories