storing something if the statement is true - php

This is a simple code I can't figure out
if(preg_match( "/where/","where's my backpack") == true){
echo "this is a match";
// this is the part i cant figure out
// how can I store it as == $match1
// I tried $match1 == "this is a match"; but it didn't work
}else{
//$match1= " "; << this what I tried and didn't work
//when I say echo match1 later, it displays this is a match even when its wrong
}
how can I store it as a variable or something for later. for example, if those two matches are true, store it as $match1 so that I can later say 'echo $match1' so that it displays "this is a match". if not just display a space.
the overall code is in php BTW

== operator checks for equality, to store something you need to use =
$match1 = '';
if(preg_match("/where/", "where's my backpack"))
$match1 = "this is a match";
else
$match1 = " ";
echo $match1;

You can assign it directly:
$match = preg_match("/where/","where's my backpack") === 1
Now you have a boolean value that you can use anywhere after this statement.
Note that I have replaced your true with 1 as that is what preg_match will return but either will work.
By the way, I realize that this is not exactly what you want but I find it easier to maintain and more reusable when I separate output texts from logic like this.

Related

PHP code supposed to check a file for an ID not working correctly

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.

In which case should I use != or !==?

I'm currently working on my first (small) PHP project going step by step teaching myself. It's going good so far but I do have a question about the following code.. and which I should use in which case..
equal:
if ($word1 != $word2) {
echo "Your words do not match, please go back and correct this.";
die(); }
identical:
if ($word1 !== $word2) {
echo "Your words do not match, please go back and correct this.";
die(); }
Th code runs fine with both of these but I would still like a detailed explanation as to when use which one, for future references, and to learn.
Thank you!
You can understand the difference between them by looking at Types comparison table in PHP manual.
Main difference is that !== is strict about type of compared values while != is weaker check.
the one will pass the other one will not the frist one cheks only for equal the second one checks and for type of var. The var $word1 is string
the $word2 is a integer
if ($word1 != $word2) {
echo "Your words do not match, please go back and correct this.";
}
//with this if stament will pass the test without echo out nothing.
if ($word1 !== $word2) {
echo "Your words do not match, please go back and correct this.";
} //this one will not pass and will echo out your string
?>

Checking similarity in php

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.

Checking for a null value in conditional in PHP

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
}

PHP Multiple condition if statement returning nothing

I have been trying to figure this out for weeks, it is a simple statement yet it never executes the if statement. I'm echoing the variables to the screen so I know they exist and each condition is true, but the echo "something" never executes.
if ($db_a==$session_a && $db_b==$session_b && $dbfreq_b=="1")
{
echo "something";
}
I thought it was just the brackets as I had this originally:
if (($db_a==$session_a) && ($db_b==$session_b) && ($dbfreq_b=="1"))
I am comparing variables stored in a MYSQL database with session variables.
If I use Var_dump the db variables are null, yet they echo the expected string value to the screen.
$db_a="username";
$session_a="username";
$db_b=="keyword string"; -mostly one word but could be multiple
$session_b=="keyword string";
$dbfreq_b="1"; - This is the frequency that the keyword appears in the MYSQL database
using vardump $db_a and $db_b are NULL yet they echo what I am expecting to see to the browser.
Hopefully this explains things a bit more?
Thank you for the very prompt help!!
If as you say $db_a = $session_a AND $db_b = $session_b AND $dbfreq_b = 1 then it's impossible that condition returns false.
Please check your code again (all 5 variables) and make sure ALL of the conditions are met.
You could just split your single IF into three separate conditions so that you know which one returns false.
if ($db_a == $session_a) {
echo "first OK\n;"
}
if ($db_b == $session_b) {
echo "second OK\n";
}
if ($dbfreq_b == "1") {
echo "third OK";
}
Could you add the values of your variables to your question?

Categories