I have a list of postcode areas (left hand part only) as below:
IV1-28,IV30-32,IV36,IV40-49,IV52-56,IV63,KW1-3,KW5-14,PA21-38,PH1-26,PH30-41,PH49-50,LD1-99,SY16-20,SY23-25
My input is a UK Postcode eg. IV21
I need a PHP function to check if the input postcode (eg IV21) is in the list.
This would be simple enough, but the list is in the form IV1-28 as opposed to being a 'normal' list such as IV1,IV2,IV3,IV4,IV5,IV6...IV26,IV27,IV28 etc.
Help is much appreciated. Thanks in advance.
loops through an array of codes and splits them into the number then checks if that number is within the range
$list = array("IV1-28","AB1-10");
$found = false;
$input = "AB10";
$inputCode = substr($input,0,2);
$inputNumber = substr($input,2);
foreach ($list as $l)
{
$lCode = substr($l,0,2);
$lNumber = substr($l,2);
$listNumbers = explode("-",$lNumber);
if (($inputNumber >= $listNumbers[0]) && ($inputNumber <= $listNumbers[1]) && ($inputCode==$lCode))
{
$found = true;
break;
}
}
var_dump($found);
http://php.net/manual/en/function.explode.php (to split your list into only the left hand side), add the left hand side into an array, and use http://php.net/manual/en/function.in-array.php - should get you somewhere close to what you need
use strpos function. returns int if found or else false. note that matching IV1 would give true even of IV11 is found. so use the following script
$code="IV21";
$list="IV1-..........etc";
if(strpos($list,$code."-") || strpos($list,$code.",") {
//true
}
else {
//false
}
the "-" and "," is to ensure that the string ends so that IV11 won't give true if we search for IV1
Related
So I'm working on a PHP app receiving a student ID from an input and searching through a file to find if the ID is present or not. If it's present, the name of the student and whether hes present or not should be printed out, and if the ID doesn't exist, it should say that there are no students with this ID.
Here is an example of what the txt file looks like:
1234|Sally Simon|1
4321|Larry Lonbottom|0
7364|Hannah Harrow|1
I made a solution and tested it, but it prints out a student name even when the ID I enter is false. Could someone give me an idea of what I'm doing wrong?
Here is my code:
<?php
$student=$_GET["student"];
$lines = file('students.txt');
foreach ($lines as $line){
$var = explode("|", $line);
}
if($student == $var[0] || $var[2] == "1"){
echo "$var[1]($var[0]): has signed up";
}else if($student == $var[0] || $var[2] == "0"){
echo "$var[1]($var[0]): hasn't signed up";
}else{
echo "No students with that id!";
}
?>
1) Your $var will always have the last line in the file, wrap everything with the foreach;
2) You should use && instead of ||
EDIT: updated code
<?php
$student=$_GET["student"];
$lines = file('students.txt');
$missing = true;
foreach ($lines as $line){
$var = explode("|", $line);
if($student == $var[0]){
$missing = false;
if($var[2] == "1"){
echo "$var[1]($var[0]): has signed up";
}else if($var[2] == "0"){
echo "$var[1]($var[0]): hasn't signed up";
}
}
}
if($missing){
echo "No students with that id!";
}
?>
As OPs said you need to change your conditional logic (if elses) and place it within the foreach loop (i.e. before the foreach's closing }.
However: (php.net file) "Each element of the array corresponds to a line in the file, with the newline still attached." so you have to remove the EOL/NL marker (invisible whitespace) from $var[2]. This can be achieved changing your file function to file('students.txt', FILE_IGNORE_NEW_LINES) however it is probably best to use trim as per example below.
It may help simplify things for you if you get rid of else conditions. try this:
<?php
$student=trim($_GET["student"]); // should also check and exit if ! digits
$lines = file('students.txt');
$isRegistered = array( "hasn't signed up", "has signed up");
$invalidID = TRUE;
foreach ($lines as $line){
$var = explode("|", $line);
if( $student == trim($var[0]) ) {
echo "$var[1]($var[0]): " . $isRegistered[ trim($var[2]) ];
$invalidID = FALSE;
break; // prevent unnecessary processing, exit foreach loop
}
}
if ( $invalidID ) echo "No students with that id!";
?>
Note: the above assumes file only contains valid content.
(1) Put the if statements inside the loop since you want to use those conditionals with every line.
(2) You are using logical 'or' operators. This means that only one of the conditions for that line need to be met.
This is what you are saying
if $student == $var[0] OR if $var[2] == 1
So regardless of what ID you enter, you always match the 0 or 1 condition.
Use the && operator instead of || if you need both conditions to be met instead of just one of the two.
(3) By using the == operator, the string will have to match with the value you are looking for exactly. You might have spaces in $student or there might be additional character in between the |. Just to air on the side of caution, remove all chances of there being hidden whitespace with your variables.
Do this: $student[0] = preg_replace('/\s+/', '', $student[0]); and do that with var[0] and var[2] as well. Do this before you run them through the if statements but still inside the loop.
Here is a link that talks about logical operators in php. It might be nice to use as a reference for future conditional statements that you need to build!
This link explains what you are doing to these values with preg_replace. It becomes very handy when you need to remove characters from a string that otherwise might difficult to deal with.
I have a very long list of strings called $stringfilter1 $stringfilter2 etc all the way up to $stringfilter50
I have another string $reporteremail and I want to make a conditional statement whereby if any of the $stringfilter strings is present in the $reporteremail, some code is executed. At the moment my code looks like this and it works:
if (stripos($reporteremail, $stringfilter1) !== false || stripos($reporteremail, $stringfilter2) !== false || stripos($reporteremail, $stringfilter3) !== false [...]) {
runcode();
}
This is very very long though. I have cut it short here.
I was wondering if there's a cleaner, more efficient way to do this?
EDIT:
I am writing a plugin for a bug tracker. The strings are entered on another page in text boxes. I access them on this page by running a function that looks like
$t_filter = plugin_config_get( 'filter1' );
$stringfilter1 = string_attribute( $t_filter1 );
I would agree looping through an array would be the best way to do this. How can I push each new string onto the end of an array without having to write that snippet above out 50 times?
How can I push each new string onto the end of an array without having to write that snippet above out 50 times?
Try this:
$needles = [];
for ($i = 0; $i < 50; $i++) {
$t_filter = plugin_config_get("filter$i");
$needles[] = string_attribute($t_filter);
}
I have a very long list of strings called $stringfilter1 $stringfilter2 etc all the way up to $stringfilter50
[...]
This is very very long though. I have cut it short here.
I was wondering if there's a cleaner, more efficient way to do this?
Try this, it should go after the code block above.
$flag = false;
foreach ($needles as $needle) {
if (stripos($reporteremail, $needle) !== false) {
$flag = true;
break;
}
}
if ($flag) {
runcode();
}
The code above works by iterating through the $needles array and sets a flag if stripos doesn't return false. After it's finished iterating, it checks if the flag is true, if so, this means that one of the needles was found in the array.
EDIT
Alternatively, you could do it all in one loop, which is both faster and more efficient.
$flag = false;
for ($i = 0; $i < 50; $i++) {
$t_filter = plugin_config_get("filter$i");
$needle = string_attribute($t_filter);
if (stripos($reporteremail, $needle) !== false) {
// One of the needles was found in $reporteremail.
runcode();
break;
}
}
You don't need a loop. First put all your filters in an array instead of having them in separate variables. I would try to do this by modifying the input source rather than doing it in your PHP script. (Based on your comments I'm not sure if that's possible or not, so maybe you do need a loop like the one in the other answer.) Then you can use str_ireplace to check for your filter strings in the $reporteremail. (This will not modify $reporteremail.)
str_ireplace($filters, '', $reporteremail, $count);
if ($count) {
// run code
}
The $count parameter will contain a count of how many replacements were performed. If it's nonzero, then at least one of the filters was found in $reporteremail.
I need to check if $string1 is like $string2 but I dont want it to matter if one text is different than the otherif it starts with the same string. For example I would like
if (admin.example2 == admin.example1)
should return true! What's the best way to do this?
My exact requirement. An if condition to check if any string is starting with admin is present in the array.
if ($client_name like 'admin') {
...
...
}
There is unlimited number of entries in an array. I just want to check if any string is present which start with "admin" is there or not.
Seems like you are looking for similar_text in PHP
<?php
similar_text("admin.example2", "admin.example1", $simpercentage);
if($simpercentage>90)
{
echo "Both strings are like ".round($simpercentage)."% similar.";
}
OUTPUT :
Both strings are like 93% similar.
Just set a percentage ratio (in the above case I have set it like 90% similarity) , You can adjust like as per your needs. The code will return 100% match if both strings are admin.example2 and admin.example2 (If both the strings are same)
As the question was edited drastically...
<?php
$arr=['admin1','administrator','admin2','I am an admin','adm','ADMIN'];
array_map(function ($v){ if(stripos(substr($v,0,5),'admin')!==false){ echo "$v starts with the text admin<br>";}},$arr);
OUTPUT :
admin1 starts with the text admin
administrator starts with the text admin
admin2 starts with the text admin
ADMIN starts with the text admin
According to your new specified requirement, if a string starts with 'admin' can be checked like this:
$your_string = 'admin.test';
if(strcmp(substr($your_string, 0, 5), "admin") == 0)
{
echo 'begins with admin';
} else {
echo 'does not begin with admin';
}
EDIT:
If you have an array of strings, example $array = array("admin.test", "test", "adminHello", "hello"), you could make a function that checks if the array contains at least one string that begins with admin:
function checkArrayStartsWithAdmin($array)
{
$result = false;
foreach($array as $key => $value)
{
if(strcmp(substr($value, 0, 5), "admin") == 0)
{
$result = true;
break;
}
}
return $result;
}
You should probably want to take a look at the concept of the levenshtein distance.
You could use this php function.
http://www.php.net/manual/es/function.levenshtein.php
I hope it helps you.
I am trying to get multiple value from user input from text field and want to explode or keep adding into if condition statement
Here is my code
foreach ($list['post'] as $item) {
if( ($item['single']['catid'] != 8) AND ($item['single']['catid'] != 4) ){
$this->list_post($item);
}
}
Now what exactly I am looking for is in if( ($item['single']['catid'] != 8) AND ($item['single']['catid'] != 4) ) I want allow user to add multiple category ID and each ID will add AND and further id code AND ($item['single']['catid'] != 4)
I never done this before and don't know either this is proper way to do or any other possible better way.
Thanks a lot
You should have some kind of an array of the category IDs you want to check for, for example:
$categories = array(8, 4);
Then you could use something like the in_array(needle, haystack) built-in function of PHP.
Your if condition would become like that one: if (!in_array($item['single']['catid'], $categories)) {.
You should be using the above, but I am going to give you an idea of how it works, so you can understand the principle for more complex issues:
function exists($target, $array) {
foreach ($array as $element) { // Go through each element in the array
if ($element == $target) { // Check to see if any element there is what you are searching for
return true; // Return true, that it does exist, and stop there.
} else {
// Just ignore it...
}
}
return false; // If you get here, it means nothing returned true, so it does not exist...
}
To be used as if (exists($item['single']['catid'], $categories)) {.
It wouldn't work if it was "inside" the if statement because you have to do some processing before evaluating if it exists or not. So you either could have done that before the if statement, and store the result in a variable, or use a function (which PHP provides).
Hopefully the concept will help you fir more complex problems...
Note: this assumes your input is in the form of an array, which you can build via various ways, if not provided as is directly.
Update:
The input you get via the input field is sent through form, to which you specify either POST or GET as a method. Assuming it is POST that you are using, this is how you'd get the input as a string as it was entered in the text field:
$categories_string = $_POST['the_name_field_in_the_input_tag'];
After that you have to understand it as a list of items, let's say separated by commas: 1,3,5,8. Then this is simply separating by commas. You can use explode($delimiter, $string). Like that:
$categories_array = explode(',', $_POST['categories']);
But you cannot trust the input, so you could get something like 1, 2, 3,5,6. The spaces will mess it up, because you will have spaces all around. To remove them you can use trim for example.
$categories = array(); // Create the array in which the processed input will go
foreach ($categories_array as $c) { // Go through the unprocessed one
$categories[] = trim($c) * 1; // Process it, and fill the result. The times one is just so that you get numbers in the end and not strings...
}
Then you can use it as shown earlier, but keep in mind that this is just an example, and you might not even need all these steps, and there are much more efficient ways to process this input (regular expressions for example). But the concern here is not sanitizing input, but keep in mind you will need to do that eventually.
Hope it's clear enough :)
You might be better off with in_array() for checking a value against a variable number of possibilities.
I'm not sure I understand your problem. You want user to be able to input different values, e.g.:
$string = "5, 6, 7, 8, 10";
Afterwards, you want to check if 'catid' is not in that array and if it isn't you want to run $this->list_post($item);
If so, then you should use something like this:
$values = explode(", ", $string); //make array from values
foreach ($list['post'] as $item) {
if (!in_array($item['single']['catid'], $values)) { //check whether catid is in array
$this->list_post($item); // execute whatever you want
}
}
Hope it helps.
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.