Can a variable be declared within a while loop? - php

I am trying to understand the basic PHP code in this video, which demonstrates how you can list all the positions of a specific string within a larger string (in this case, all the positions of $find within $string will be listed):
<?php
$find = 'is';
$find_leng = strlen($find);
$string = 'This is a string, and it is an example.';
while ($string_position = strpos($string, $find, $offset)) {
echo '<strong>'.$find.'</strong> found at '.$string_position.'<br>';
$offset = $string_position + $find_length;
}
?>
What confuses me is that within the () of the while-loop, it seems that a new variable $string_position is being declared. But doesn't the while-loop take an input of 0 or 1, a Boolean? The $string_position variable is not a true/false variable, it is meant to store the position of the string it is passed with the strpos() function.
The basic while-loop I'm used to uses a comparison operator like this one from from w3schools:
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
Can a variable be declared in a while-loop? And if that is the case, how does it work in this example? This is my first question on Stack Overflow so hopefully I'm posting this in the right place and it's not too newbie of a question.

Yes, while loops take boolean-like as arguments. By doing
while ($string_position = strpos($string, $find, $offset)) {
it first executes what is inside the parenthesis, then evaluates the result of that to determine if the loop should quit or not.
strpos will return False if the needle was not found, so $string_position will be false and as such the evaluation result will also be False and the loop will quit. If the needle is found, then loop continues after the attribution.
Also it should be noted that strpos might return a non-boolean that evaluates to False, so be careful with that construction.
Reference on strpos

In most programming languages, if a variable exists and isn't 0 or False, then it counts as a 1 or True.
In this example:
if ($str="hey"){
echo $str;
};
It will output hey because the variable was successfully declared and isn't 0.

Related

Creating a New Variable Based On a Matched Array ID Value [duplicate]

<?php
$a = 'abc';
if($a among array('are','abc','xyz','lmn'))
echo 'true';
?>
Suppose I have the code above, how to write the statement "if($a among...)"?
Use the in_array() function.
Manual says:
Searches haystack for needle using loose comparison unless strict is set.
Example:
<?php
$a = 'abc';
if (in_array($a, array('are','abc','xyz','lmn'))) {
echo "Got abc";
}
?>
Like this:
if (in_array($a, array('are','abc','xyz','lmn')))
{
echo 'True';
}
Also, although it's technically allowed to not use curly brackets in the example you gave, I'd highly recommend that you use them. If you were to come back later and add some more logic for when the condition is true, you might forget to add the curly brackets and thus ruin your code.
There is in_array function.
if(in_array($a, array('are','abc','xyz','lmn'), true)){
echo 'true';
}
NOTE:
You should set the 3rd parameter to true to use the strict compare.
in_array(0, array('are','abc','xyz','lmn')) will return true, this may not what you expected.
Try this:
if (in_array($a, array('are','abc','xyz','lmn')))
{
// Code
}
http://php.net/manual/en/function.in-array.php
in_array — Checks if a value exists in an array
bool in_array ( mixed $needle , array $haystack [, bool $strict =
FALSE ] ) Searches haystack for needle using loose comparison unless
strict is set.

Search php string - %like% sql

Right now I use stristr($q, $string) but if
$string = "one monkey can jump 66 times";
$q = "monkey 66";
I want to find out if this string contains both monkey and 66.
How can i do that?
you could use both stristr and strpos.
as it is reported in this post, the second method is faster and less memory intensive.
well, check this lines out:
// here there are your string and your keywords
$string = "one monkey can jump 66 times";
$q = "monkey 66";
// initializate an array from keywords in $q
$q = explode(" ", $q);
// for every keyword you entered
foreach($q as $value) {
// if strpos finds the value on the string and return true
if (strpos($string, $value))
// add the found value to a new array
$found[] = $value;
}
// if all the values are found and therefore added to the array,
// the new array should match the same object of the values array
if ($found === $q) {
// let's go through your path, super-man!
echo "ok, all q values are in string var, you can continue...";
}
if(stristr('monkey', $string) && stristr('66', $string)) {
//Do stuff
}
simply post your variable value by giving them a variable $monkey,$value ($monkey jumps $value) and then fetch its value
You can use the strpos() function which is used to find the occurrence of one string inside another one:
$a = 'How are you?';
if (strpos($a, 'are') !== false) {
echo 'true';
}
Note that the use of !== false is deliberate (neither != false nor === true will work); strpos() returns either the offset at which the needle string begins in the haystack string, or the boolean false if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like !strpos($a, 'are').

Am i using strpos correctly?

I am trying to determine whether a word is present within a string of text, then if the word is present, print the relevant string. I'm having issues because this code appears to be working for some of my users but not all of them.
$active = $db->query("SELECT * FROM activity ORDER BY aTIME DESC LIMIT 15");
while($activity = $db->fetch_row($active))
{
$haveact = $activity['activity'];
$username = $r['username'];
if(strpos($haveact, $username))
{
print " <div class='activitydiv'>
{$activity['activity']} &nbsp&nbsp&nbsp&nbsp<small><font color='grey'>
{$activity['aTIME']}</font></small>
</div>";
}
}
Apart from what is suggested in the other answers, I would re-write the whole code to perform the string search in the query. For example like this:
<?php
$active = $db->query("SELECT * FROM (SELECT * FROM activity
ORDER BY aTIME DESC LIMIT 15)
WHERE activity LIKE \"%" . $db->escape($r['username']) . "%\";");
while($activity=$db->fetch_row($active))
{
print "<div class='activitydiv'>
{$activity['activity']} &nbsp&nbsp&nbsp&nbsp<small><font color='grey'>
{$activity['aTIME']}</font></small>
</div>";
}
?>
Please note that strpos returns the position of the found text. So for instance, when the word you are searching for is at the beginning of the the string the function will return '0'. Given that 0 is a false value, when you use the function like you did even though the word is found it will not be true. The correct usage of strpos is:
if (strpos($haystack, $needle) !== false) // Note the type check.
{
// your code...
}
Moreover, this function is case sensitive by default. You can use stripos for case insensitive search.
EDIT
From the manual:
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE
Check the following examples to understand better:
strpos('the quick brown fox jumps over the lazy dog', 'the'); // Returns 0 (false value)
strpos('the quick brown fox jumps over the lazy dog', 'quick'); // Returns 4 (true value)
strpos('the quick brown fox jumps over the lazy dog', 'THE'); // Returns false (case sensitive)
Like Hauke P. mentioned - don not do this with PHP. You WANT to filter the matching rows with your database. If you do not want to use WHERE row LIKE %foo% because you need more power, you can even use REGEX in MYSQL. Just do not process the data with PHP. It is a design failure if you do so.
Check out the MySQL Help files about LIKE, SELECT, and REGEX.
hint: http://www.mysql.com/
strpos has the possibilty to return 0 and FALSE which are basically the same "value"
you need to check type and value like
strpos($haveact,$username) !== FALSE
strpos() returns a boolean FALSE if needle isn't found; and an integer value for its offset in the string if it is found. That offset can be 0, which equates to Boolean FALSE in a loose comparison.
Use
if(strpos($haveact, $username) !== FALSE)
as an alternative you can try php's preg_match function :
if (preg_match("/{$to_search}/" , $subject)) {
// your code to process
}
Another option, I usually use because it's shorter :)
if (strpos($haveact, $username) !== false) {
// In string.
}

PHP strpos to match querystring text pattern

I need to execute a bit of script only if the $_GET['page'] parameter has the text "mytext-"
Querystring is: admin.php?page=mytext-option
This is returning 0:
$myPage = $_GET['page'];
$match = strpos($myPage, 'mytext-');
echo $match;
strpos returns the position of the string. Since it's 0, that means it was found at position 0, meaning, at the start of the string.
To make an easy way to understand if it's there, add the boolean === to an if statement like this:
<?php
$myPage = $_GET['page'];
$match = strpos($myPage, 'mytext-');
if ( $match === false ) {
echo 'Not found';
} else {
echo 'Found';
}
?>
This will let you know, if the string is present or not.
Or, if you just need to know, if it's there:
$myPage = $_GET['page'];
$match = strpos($myPage, 'mytext-');
if ( $match !== false ) {
echo 'Found';
}
?>
Use substr() once you get the location of 'mytext-', like so:
$match = substr($myPage, strpos( $myPage, 'mytext-') + strlen( 'mytext-'));
Otherwise, strpos() will just return the numerical index of where 'mytext-' starts in the string.
You can also use str_replace() to accomplish this if your string only has 'mytext-' once:
$match = str_replace( 'mytext-', '', $myPage);
The function strpos() returns the position where the searched string starts which is 0. If the string is not found, the function will return false. See the strpos documentation which tells you as well:
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.
A solution to your question would be to use substr(), preg_match() or check if strpos() !== false.
The easiest solution should be this:
if (preg_match('/^mytext-/i', $_GET['page'])) {
// do something
}
You may also consider using more than just one GET parameter like
http://www.example.com/foo.php?page=mysite&option1=123&option2=456
You then use your parameters lik $_GET['page'], $_GET['option1'], $_GET['option2'], etc.
However, you should also be careful what you do with raw $_GETor $_POST data since users can directly input them and may inject harmful code to your website.
That is expected since the substring starts at index 0. Read the warning on php.net/strpos:
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.
If you only need to check if $myPage contains 'mytext-', use stristr:
if(stristr($myPage, 'mytext-') !== false) {
// contains..
}
What's wrong about preg_match?
$myPage = $_GET['page'];
if (preg_match("/\bmytext-\b/i", $myPage)) {
//Do Something
}
Or do you need the "option" out of "mytext-option"?
If yes you can use this:
$myPage = $_GET['page'];
$querystrings = explode("-", $myPage);
if ($querystrings[0] == 'mytext')) {
//Do Something
echo $querystrings[1]; //outputs option
}
With this you can even use more "options" in your querystring like "mytext-option-whatever". That's the same as when you use
$_GET['page'], $_GET['option'], $_GET['whatever']
when you use
?page=mysite&option=x&whatever=y

PHP equivalent of indexOf

I have the following JS:
if(window.location.href.indexOf("search.php") != -1
|| window.location.href.indexOf("list.php") != -1
|| window.location.href.indexOf("view.php") != -1
|| window.location.href.indexOf("contact.php") != -1) {
But want to convert it to PHP. What is the equivalent of indexOf in PHP or the best way to do this in PHP.
I don't understand the strpos examples people are linking to below. Perhaps an example more in line with what I have done in JS?
The question asks for an equivalent. PHP's strpos() does not work on an array, whereas javascript's indexOf does (by treating a string as an array automatically). So here's a PHP equivalent
function indexOf($array, $word) {
foreach($array as $key => $value) if($value === $word) return $key;
return -1;
}
// Example: indexOf(['hi','bye'], 'bye') returns 1
Although your JavaScript code is using indexOf(), PHP actually has a better way of handling what you want to achieve.
You simply have to check the script name in your URL, then perform an action(s) based on it.
In my opinion, PHP switch statement is better than if statements in combination with PHP strpos() function.
Below is an illustration of how you can achieve that using a PHP switch statement:
switch(basename($_SERVER['SCRIPT_NAME'])) {
case 'search.php':
// Script to run for search.php
break;
case 'list.php':
// Script to run for list.php
break;
case 'view.php':
// Script to run for view.php
break;
case 'contact.php':
break;
default:
// Perform code on anything except the above cases.
break;
}
strpos() should do the trick, also it returns boolean false on failure.
JS version:
The indexOf() method returns the position of the first occurrence of a
specified value in a string. This method returns -1 if the value to
search for never occurs. Note: The indexOf() method is case sensitive.
PHP version:
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
Find the numeric position of the first occurrence of needle in the
haystack string. Returns the position of where the needle exists relative to the
beginning of the haystack string (independent of offset). Also note
that string positions start at 0, and not 1. Returns FALSE if the
needle was not found.
In reply to your secondary question, strpos could be used as follows:
if (strpos($_SERVER['SCRIPT_NAME'], "search.php") !== false
|| strpos($_SERVER['SCRIPT_NAME'], "list.php") !== false
|| strpos($_SERVER['SCRIPT_NAME'], "view.php") !== false
|| strpos($_SERVER['SCRIPT_NAME'], "contact.php") !== false) {
...though indeed Rawkode's answer is more elegant.
strpos();
You should use mb_strpos() if you're not using ISO-8859-1 encoding (UTF-8 or others).

Categories