Is there an isdate PHP function? - php

I saw an inbuilt function called isdate in the user function below and when I checked the PHP documentation I didn't find it. Does it exist and what does it do; or is this simply a typo?
function mystery($a, $b, $c) {
$result = null;
if (strlen(trim($a)) == 0) {
$result = $c;
}
else {
if (strtolower(trim($b)) == "n") {
if (!is_numeric($a)) {
$result = $c;
}
else {
$result = trim($a);
}
}
else {
if (strtolower(trim($b)) == "d") {
if (!isdate($a)) {
$result = $c;
}
else {
$result = trim($a);
}
}
else {
$result = $a;
}
}
}
return($result);
}

Perhaps, this isn't really an answer since I don't know what the original function is for and to be honest I don't care. Whatever, you can do several simplifications to make it more readable, to avoid duplicate processing, the useless $result variable and in particular to remove these unreadable nested if/else, in other words to remove all this useless noise:
function mystery($a, $b, $c) {
$trima = trim($a);
if ( empty($trima) )
return $c;
$b = strtolower(trim($b));
if ( $b == "n" )
return is_numeric($trima) ? $trima : $c ;
if ( $b == "d" )
return isdate($trima) ? $trima : $c ;
return $a;
}
I hope this will help you to understand what this function is supposed to do (perhaps a context will be helpful).

Related

how to write recursion using loops

I want to write recursive code using loops instead of recursion function. because recursion take too much time to execute and even fails.This is counting user in both side of binary tree using recursion.i want to achieve this task using loops. please help me to achieve this task.thanks in advance.I will very thank full to you.
function countActiveMembers($mid){
if ($mid == null) {
return 0;
}
$c = 0;
include("conn.php");
$query = $conn->prepare('SELECT leftm, rightm, package_choose FROM member WHERE user_id = ?');
$query->bind_param('s', $mid);
$query->execute();
$query->bind_result($leftm, $rightm, $package_choosen);
if ($query->fetch()) {
$query->close();
$conn->close();
if ($package_choosen == 1) {
$c = 0;
} else {
$c = 1;
}
if (isset($leftm) == false && isset($rightm) == false) {
return $c;
}
if (isset($leftm)) {
$c = $c + countActiveMembers($leftm);
}
if (isset($rightm)) {
$c = $c + countActiveMembers($rightm);
}
} else {
$query->close();
$conn->close();
}
return $c;
}
function countLeftActive($mid){
if ($mid == null) {
return 0;
}
$c = 0;
include("conn.php");
$query = $conn->prepare('SELECT leftm, rightm, package_choose FROM member WHERE user_id = ?');
$query->bind_param('s', $mid);
$query->execute();
$query->bind_result($leftm, $rightm, $package_choosen);
if ($query->fetch()) {
$query->close();
$conn->close();
if (isset($leftm) == false && isset($rightm) == false) {
return 0;
}
if (isset($leftm)) {
$c = $c + countActiveMembers($leftm);
}
} else {
$query->close();
$conn->close();
}
return $c;
}
function countRightActive($mid){
if ($mid == null) {
return 0;
}
$c = 0;
include("conn.php");
$query = $conn->prepare('SELECT leftm, rightm, package_choose FROM member WHERE user_id = ?');
$query->bind_param('s', $mid);
$query->execute();
$query->bind_result($leftm, $rightm, $package_choosen);
if ($query->fetch()) {
$query->close();
$conn->close();
if (isset($leftm) == false && isset($rightm) == false) {
return 0;
}
if (isset($rightm)) {
$c = $c + countActiveMembers($rightm);
}
} else {
$query->close();
$conn->close();
}
return $c;
}
I hope you can appreciate that this is difficult to test, so hopefully you can understand it enough to help.
One of the big performance issues in any system is file/database access and opening and closing connections etc. is always a slow process. This routine loads all the members in the start and passes the data around rather than continually using the database...
function countActiveMembers( $members, $mid){
if ($mid == null) {
return 0;
}
$c = 0;
// Fetch the data from the $members list, using $mid as the index
$leftm = $members[$mid]['leftm'];
$rightm = $members[$mid]['rightm'];
$package_choosen = $members[$mid]['package_choose'];
if ($package_choosen == 1) {
$c = 0;
} else {
$c = 1;
}
if (isset($leftm) == false && isset($rightm) == false) {
return $c;
}
if (isset($leftm)) {
$c = $c + countActiveMembers($members, $leftm);
}
if (isset($rightm)) {
$c = $c + countActiveMembers($members, $rightm);
}
return $c;
}
function countLeftActive($members, $mid){
if ($mid == null) {
return 0;
}
$c = 0;
$leftm = $members[$mid]['leftm'];
$rightm = $members[$mid]['rightm'];
if (isset($leftm) == false && isset($rightm) == false) {
return 0;
}
if (isset($leftm)) {
$c = $c + countActiveMembers($members, $leftm);
}
return $c;
}
function countRightActive($members, $mid){
if ($mid == null) {
return 0;
}
$c = 0;
$leftm = $members[$mid]['leftm'];
$rightm = $members[$mid]['rightm'];
if (isset($leftm) == false && isset($rightm) == false) {
return 0;
}
if (isset($rightm)) {
$c = $c + countActiveMembers($members, $rightm);
}
return $c;
}
// Use your own database credentials
$conn = mysqli_connect("172.17.0.3", "root","a177fgvTRw", "test" );
$result = $conn->query('SELECT user_id, leftm, rightm, package_choose
FROM member');
$members = [];
// Read all the members in and index them by the user_id
while ($row = $result->fetch_assoc()) {
$members[$row["user_id"]] = $row;
}
// Not entirely sure how you use it,but this shows passing the members into the start function
echo countActiveMembers($members, 1);

A better way than using multiple elseif statements?

Is there a cleaner way to achieve a similar result, but without using all of these elseif statements? I need there to always be a true statement, depending on dynamic variables. Thanks!
$a = true;
$b = false;
$c = false;
if ($a == true && $b == false && $c == false) {
echo 'only $a is running';
} elseif ($a == true && $b == false && $c == true) {
echo '$a and $c are running, but not $b';
} elseif ($a == true && $b == true && $c == false) {
echo '$a and $b are running, but not $c';
} elseif ($a == false && $b == true && $c == true) {
echo '$b and $c are running, but not $a';
} elseif ($a == false && $b == false && $c == true) {
echo 'only $c is running';
} elseif ($a == false && $b == true && $c == false) {
echo 'only $b is running';
} else {
echo 'nope';
};
Consider to use an array, that way you can make more alphabet letters than you have in your example right now, and it will just work:
<?php
$arr = [
'a' => true,
'b' => true,
'c' => true
];
$running = [];
$not_running = [];
foreach($arr as $key=>$val)
if ($val)
$running[] = $key;
else
$not_running[] = $key;
if (count($running) == 0)
echo "Nope";
else if (count($running) == 1)
echo "Only ".$running[0]." is running";
else if (count($not_running) == 0)
echo "All are running";
else
echo "Only " . implode($running, ' and ') . " are running, but not ". implode($not_running, ' and ');
So now you can make your array bigger, for example like this:
for($i=0; $i<=25; $i++)
{
$arr[chr($i+97)] = (bool)rand(0,1);
}
which will output something like:
Only c and d and e and f and g and h and l and m and n and q and u and w and y and z are running, but not a and b and i and j and k and o and p and r and s and t and v and x
Here is one potential way you could do it by utilising __toString(), it's pretty rushed so you'll probably want to clean it up a bit. You can find a working example here
You may want to play with the __toString() return to get it to what you want, but essentially you just have to echo the collection.
Side note: I didn't implement Countable, ArrayAccess, Iterator or any other useful inbuilt interfaces due to time constraints. If you were to use this solution i'd suggest implementing them
<?php
class Instance
{
/** #var string */
private $name;
/** #var bool */
private $active;
public function __construct($name, $active = false)
{
$this->name = $name;
$this->active = $active;
}
public function turnOn()
{
$this->active = true;
}
public function turnOff()
{
$this->active = false;
}
public function getName()
{
return $this->name;
}
public function getActive()
{
return $this->active;
}
public function __toString()
{
$state = $this->getActive() === true ? 'on' : 'off';
return sprintf("%s is switched %s", $this->getName(), $state);
}
}
class InstanceCollection
{
private $collection = [];
public function add(Instance $item)
{
$this->collection[] = $item;
}
public function __toString()
{
$on = $this->getInstancesByState(true);
$off = $this->getInstancesByState(false);
return rtrim(implode(', ', $on), ', ') . rtrim(implode(', ', $off), ', ');
}
public function getInstancesByState($state)
{
return array_map(function($instance) use ($state) {
if ($instance->getActive() === $state) {
return $instance;
}
}, $this->collection);
}
}
Usage:
$instance = new Instance('eu');
$instance->turnOn();
$instance2 = new Instance('us');
$instance2->turnOff();
$collection = new InstanceCollection();
$collection->add($instance);
$collection->add($instance2);
echo $collection;
And output:
eu is switched on, us is switched off

Is string a math expression?

How can I found if string is a math expression or not?
It is enough to understand basic math expressions +, -, x, /
For Example:
"1+1" => TRUE
"2 / 2" => TRUE
"hello" => FALSE
"1 * 2 - X" => FALSE
"me + u" => FALSE
class MathExpression {
private static $parentheses_open = array('(', '{', '[');
private static $parentheses_close = array(')', '}', ']');
protected static function getParenthesesType( $c ) {
if(in_array($c,MathExpression::$parentheses_open)) {
return array_search($c, MathExpression::$parentheses_open);
} elseif(in_array($c,MathExpression::$parentheses_close)) {
return array_search($c, MathExpression::$parentheses_close);
} else {
return false;
}
}
public static function validate( $expression ) {
$size = strlen( $expression );
$tmp = array();
for ($i=0; $i<$size; $i++) {
if(in_array($expression[$i],MathExpression::$parentheses_open)) {
$tmp[] = $expression[$i];
} elseif(in_array($expression[$i],MathExpression::$parentheses_close)) {
if (count($tmp) == 0 ) {
return false;
}
if(MathExpression::getParenthesesType(array_pop($tmp))
!= MathExpression::getParenthesesType($expression[$i])) {
return false;
}
}
}
if (count($tmp) == 0 ) {
return true;
} else {
return false;
}
}
}
//Mathematical expressions to validate
$tests = array(
'(A1+A2*A3)+A5+(B3^B5)*(C1*((A3/C2)+(B2+C1)))',
'(A1+A2*A3)+A5)*C1+(B3^B5*(C1*((A3/C2)+(B2+C1)))',
'(A1+A2*A3)+A5++(B2+C1)))',
'(A1+A2*A3)+A5+(B3^B5)*(C1*(A3/C2)+(B2+C1))'
);
// running the tests...
foreach($tests as $test) {
$isValid = MathExpression::validate( $test );
echo 'test of: '. $test .'<br>';
var_dump($isValid);
}
you can check and read in detail about the solution here Is there possible to check mathematical expression string?
See also eval. For example, you can do this:
$result = INF;
try {
eval("$result=" + myMathExpression); // Evaluate here
} catch (Exception $e) {
}
if($result != INF) echo("Expression is a valid mathematical expression.");
read more about it there
An extremely simple solution:
Regex number,whitespace,[+,/,*,-,=],whitespace,Substring(recursion here)
will work for any sequence of
1 + 1 + 2 + ... + 1 = 2 + 3 + 4 = 1 * 4 ...
etc.
Obviously would not check if an expression is legit.
As per request, pseudo code:
if Regex(^(([0-9]+)(\s*)([+,/,*,-,=])(\s*)([0-9]+)(\s*)([+,/,*,-,=])(\s*)))
if (recursion())
return True;
else
return False;
else //checking for end point
if Regex(^(([0-9]+)(\s*)([+,/,*,-,=])(\s*)([0-9]+)))
return True;
else
return False;
Maybe a regex with a pattern like this :
^([-+/*]\d+(\.\d+)?)*

Using PHP write an anagram function?

Using PHP write an anagram function? It should be handling different phrases and return boolean result.
Usage:
$pharse1 = 'ball';
$pharse2 = 'lbal';
if(is_anagram($pharse1,$pharse2)){
echo $pharse1 .' & '. $pharse2 . ' are anagram';
}else{
echo $pharse1 .' & '. $pharse2 . ' not anagram';
}
There's simpler way
function is_anagram($a, $b) {
return(count_chars($a, 1) == count_chars($b, 1));
}
example:
$a = 'argentino';
$b = 'ignorante';
echo is_anagram($a,$b); // output: 1
$a = 'batman';
$b = 'barman';
echo is_anagram($a,$b); // output (empty):
function is_anagram($pharse1,$pharse2){
$status = false;
if($pharse1 && $pharse2){
$pharse1=strtolower(str_replace(" ","", $pharse1));
$pharse2=strtolower(str_replace(" ","", $pharse2));
$pharse1 = str_split($pharse1);
$pharse2 = str_split($pharse2);
sort($pharse1);
sort($pharse2);
if($pharse1 === $pharse2){
$status = true;
}
}
return $status;
}
function check_anagram($str1, $str2) {
if (count_chars($str1, 1) == count_chars($str2, 1)) {
return "This '" . $str1 . "', '" . $str2 . "' are Anagram";
}
else {
return "This two strings are not anagram";
}
}
ECHO check_anagram('education', 'ducatione');
I don't see any answers which have addressed the fact that capital letters are different characters than lowercase to count_chars()
if (isAnagram('Polo','pool')) {
print "Is anagram";
} else {
print "This is not an anagram";
}
function isAnagram($string1, $string2)
{
// quick check, eliminate obvious mismatches quickly
if (strlen($string1) != strlen($string2)) {
return false;
}
// Handle uppercase to lowercase comparisons
$array1 = count_chars(strtolower($string1));
$array2 = count_chars(strtolower($string2));
// Check if
if (!empty(array_diff_assoc($array2, $array1))) {
return false;
}
if (!empty(array_diff_assoc($array1, $array2))) {
return false;
}
return true;
}
here is my variant :
public function is_anagram($wrd_1, $wrd_2)
{
$wrd_1 = str_split ( strtolower ( utf8_encode($wrd_1) ) );
$wrd_2 = str_split( strtolower ( utf8_encode($wrd_2) ) );
if ( count($wrd_1)!= count($wrd_2) ) return false;
if ( count( array_diff ( $wrd_1 ,$wrd_2) ) > 0 ) return false;
return true;
}
Heheh little large but work as well :)
public static function areStringsAnagrams($a, $b)
{
//throw new Exception('Waiting to be implemented.');
$a = str_split($a);
$test = array();
$compare = array();
foreach ($a as $key) {
if (!in_array($key, $test)) {
array_push($test, $key);
$compare[$key] = 1;
} else {
$compare[$key] += 1;
}
}
foreach ($compare as $key => $value) {
if ($value !== substr_count($b, $key)) {
return false;
}
}
return true;
}

Why does this PHP function cycle endlessly?

function nonrecgen($min, $max, $amount) {
for($i=0;$i<$amount;$i++) {
$NrArray[$i] = rand($min,$max);
echo $NrArray[$i];
do {
for($j=0;$j<=$i;$j++) {
if ($NrArray[$j] == $NrArray[$i]) {
$NrArray[$i] = rand($min,$max); }
}
$Reccuring = false;
if ($i > 0) {
for($k=0;$k<=$i;$k++) {
if ($NrArray[$k] == $NrArray[$i]) {
$Reccuring = true; }
}
}
}
while ($Reccuring = true);
}
Return $NrArray;
}
$Test = nonrecgen(0,1,2);
print_r($Test);
I wanted to look into how to generate an array of nonreccuring numbers and while this is certainly not the most efficient way I believe, I can't seem to figure out why it loops endlessly on the first iteration. I tried logical analysis over and over, but there has to be something I'm missing.
do {
...
} while ($Reccuring = true);
Because your while statement sets $Reccuring to true, instead of evaluating it.
Try:
do {
...
} while ($Reccuring === true);
Other than the = to == you were also resetting the $Recurring in the wrong place:
<?
function nonrecgen($min, $max, $amount)
{
for($i=0;$i<$amount;$i++)
{
$NrArray[$i] = rand($min,$max);
do
{
for($j=0;$j<=$i;$j++)
{
if ($NrArray[$j] == $NrArray[$i])
{
$NrArray[$i] = rand($min,$max);
}
}
if ($i > 0)
{
for($k=0;$k<=$i;$k++)
{
if ($NrArray[$k] == $NrArray[$i])
{
$Reccuring = true;
}
}
}
$Reccuring = false;
}
while ($Reccuring == true);
}
return $NrArray;
}
$Test = nonrecgen(0,2,5);
echo "<pre>";
print_r($Test);
?>
You're currently assigning a value rather than checking (which will always be true).
Change it to: while ($Reccuring == true);

Categories