Check if two strings start with the same character - php

I'm trying to do this in Object Oriented PHP, but I have an issue when recursion is used (if the first string starts with a "(", I want to check the following char), the other cases work. Here is the code:
public static function different_first($item,$item1) {
if (substr($item, 0, 1) != substr($item1, 0, 1)) {
return TRUE;
} else if (substr($item,0,1)=="(") {
Object::different_first(substr($item, 1), $item1);
} else {
return FALSE;
}
}

You are missing a return:
return Object::different_first(substr($item, 1), $item1);

Missing the return as Mark mentioned. I made a few improvements to your code. This would run a lot faster.
public static function different_first($item,$item1) {
if ($item{0} == $item1{0}){
return false;
}elseif ($item{0}=="(") {
return Object::different_first($item{1}, $item1);
} else {
return true;
}
}

Related

use the functions without its parameters

I am using 2 regex functions here and I wanna make another function which returns false when the 2 regex are both false and if not, then true.
The problem here is when I wanna use the 2 regex functions in the third one, I have to give them parameters, which is not necessary I think, because the third function will only return a simple true or false. I get an undefined variable whenever I give parameters to the 2 regex functions in the 3rd one.
I tried using global variables which works but since its a bad practice I am looking for a better solution.
Code:
function regex1($input)
{
$regex= "/^[A-Za-z0-9 ]*$/";
if (!preg_match($regex, $input))
{
return false;
}
else
{
return true;
}
}
function regex2($input)
{
$regex= "/^[A-Za-z0-9 ]*$/";
if (!preg_match($regex, $input))
{
return false;
}
else
{
return true;
}
}
function checkBoth()
{
if (regex1($input) === false || regex2($input) === false)
{
return false;
}
else
{
return true;
}
}
EDIT:
The checkBoth function I am using in my other file like this together with the other 2 regex functions:
if (!regex1($input))
{
// show error at the same time
}
if (!regex2($input))
{
// show error at the same time
}
if(checkBoth())
{
// success
}
function regex2($input,$secondVar=false)
{....
Later in code in place where you need just add:
if($secondVar !== false){
// do whatever...
}
If you can't user "false" you can just empty string '' or any other value that will not appear there.

How to check (strpos(...)) all elements of an array efficiently?

I want to check all elements of an array and find out, whether at least one of them is prefixed by a given string:
public function validateStringByPrefix(string $string, $prefix)
{
$valid = false;
if (is_string($prefix)) {
if (strpos($string, $prefix) === 0) {
$valid = true;
}
} elseif (is_array($prefix)) {
foreach ($prefix as $partPrefix) {
if (strpos($string, $partPrefix) === 0) {
$valid = true;
break;
}
}
}
return $valid;
}
Is it possible / How to to achieve the same a more efficient way?
(It's a cheap method, but it's called a lot of times in my application, so even a minimal improvement might appreciably increase the application's performance.)
You can try next solution:
public function validateStringByPrefix(string $string, $prefix)
{
return (bool)array_filter((array)$prefix, function($prefix) use ($string) {
return strpos($string, $prefix)===0;
});
}
P.S. In case you have few large arrays (with prefixes), my solution is less efficient and you can combine our approaches like this:
public function validateStringByPrefix(string $string, $prefix)
{
if($string=='') {
return false;
}
foreach ((array)$prefix AS $subprefix) {
if (strpos($string, $subprefix)===0) {
return true;
}
}
return false;
}
There are many ways to rome....
//your array to test for
$array=[];
//set valid to false
$valid=false;
//setup prefixes array or not
$prefix='whatever';
//make array if you dont have one
!is_array($prefix) AND $prefix=array($prefix);
//prepare for use as REGEX
$prefix=implode('|',$prefix);
//do the work
array_walk($array,function($val,$key) use(&$valid,$prefix){
if (!$valid && preg_match("#^($prefix)#",$key)) {
$valid = true;
}
});
var_export($valid);
I used preg_match here, because $prefix can be an array, so the math would be: n+ strpos() calls vs. one preg_match() call
And after a single item matches, no more preg_match are called, just iteration to the end and out.

Return an empty but tell php it means `return false`

Is it possible to return an array, but also tell php it's supposed to mean false?
Example:
if ($res = a_function()) {
// all good
}
else {
echo getErrorByNumber($res['err_no']);
}
a_function:
function a_function() {
// do fancy stuff
if (xy) return true;
return array('err_no' => 1);
}
I guess its not possible, since php will always take an array for return true, right?
Lot's of ways. Probably the preferred one, compare to true with type checking ===:
if(($res = a_function()) === true) {
// all good
}
else {
echo getErrorByNumber($res['err_no']);
}
A non-empty array will always be true:
if($res = a_function() && !is_array($res)) {
// all good
}
else {
echo getErrorByNumber($res['err_no']);
}
Or flip it around:
if(is_array($res)) { //or isset($res['err_no'])
echo getErrorByNumber($res['err_no']);
}
else {
// all good
}
I would solve this problem with a byref parameter:
function foo(&$errors)
{
if (allWentWell())
{
$errors = null;
return true;
}
else
{
$errors = array('err_no' => 007);
return false;
}
}
// call the function
if (foo($errors))
{
}
else
{
echo getErrorByNumber($errors['err_no']);
}
This way you do not have to distinguish between different possible return types and you will not run into type juggling problems. It is also more readable, you know what's inside the $errors variable without documentation. I wrote a small article explaining why mixed-typed return values can be so dangerous.

PHP : Function - Return 2 variables (Boolean + $variable)

Issue Resolved : Here is the solution :
function testCoreq()
{
$coreqTest = makeCoreq();
if(empty($coreqTest))
{
return array(true);
break;
}
else
{
foreach ($coreqTest as $ctest)
{
if($ctest['value'] == "true")
{
return array(true);
break;
}
else
{
return array(false,$ctest['coreqID']);
}
}
}
}
if(testCoreq()[0])
{
//do something
}
else
{
return testCoreq()[1]
}
I'm doing a school project and hit kind of a bump.
I created a function and i want it to either return "true" (boolean) or "false" (boolean) + a variable.
I searched the net quite a bit but wan't able to find a simple way to do this .
Is there any way to this this ? //Thanks
The function is working properly but when it is returning the variable - it is also assuming that the function is returning "true" when i want it to return false + the value like :
else
{
return $ctest['coreqID'];
return false;
}
Here is the code :
function testCoreq()
{
$coreqTest = makeCoreq();
if(empty($coreqTest))
{
return true;
break;
}
else
{
foreach ($coreqTest as $ctest)
{
if($ctest['value'] == "true")
{
return true;
break;
}
else
{
return $ctest['coreqID'];
}
}
}
}
I am using it like this:
if (testCoreq())
{
// do something
}
else
{
// return the variable
}
but even if the first statement is false , then it is returning the variable - it is assuming the function is true.
You can try to return -1 on true and other for false to decrease amount of returning values. Next option is to return array of values. The other option would be to pass reference variable in the function.

float Number validation check for codeigniter

Here I am entering tax field in % but when i enter values like 2.5,0.5 other than integer it is generating error.
Here is my code for Validation,any idea for entering float numbers
function _set_rules()
{
$this->form_validation->set_rules('pst','PST','trim|required|is_natural|numeric|
max_length[4]|callback_max_pst');
$this->form_validation->set_rules('gst','GST','trim|required|is_natural|numeric|
max_length[4]|callback_max_gst');
}
function max_pst()
{
if($this->input->post('pst')>100)
{
$this->form_validation->set_message('max_pst',' %s Value Should be less than or equals to 100');
return FALSE;
}
return TRUE;
}
function max_gst()
{
if($this->input->post('gst')>100)
{
$this->form_validation->set_message('max_gst',' %s Value Should be less than or equals to 100');
return FALSE;
}
return TRUE;
}
</code>
remove the is_natural from the validation rules and replace it with greater_than[0] and less_than[100]
function _set_rules()
{
$this->form_validation>set_rules('pst','PST','trim|required|
greater_than[0]|less_than[100]|max_length[4]|callback_max_pst');
$this->form_validation->set_rules('gst','GST','trim|required|
greater_than[0]|less_than[100]|max_length[4]|callback_max_gst');
}
greater_than[0] will apply numeric
From the codeigniter documentation:
is_natural Returns FALSE if the form element contains anything other than a natural number: 0, 1, 2, 3, etc. source
Clearly, values like 2.5,0.5 are not natural numbers so they will fail validation. You can use a callback and return the value after parsing the value with floatval() PHP function.
Hope it helps!
You can try this :
function _set_rules()
{
$this->form_validation>set_rules('pst','PST','trim|required|
numeric|max_length[4]|callback_max_pst');
$this->form_validation->set_rules('gst','GST','trim|required|
numeric|max_length[4]|callback_max_gst');
}
function max_pst($value) {
$var = explode(".", $value);
if (strpbrk($value, '-') && strlen($value) > 1) {
$this->form_validation->set_message('max_pst', '%s accepts only
positive values');
return false;
}
if ($var[1] > 99) {
$this->form_validation->set_message('max_pst', 'Enter value in
proper format');
return false;
} else {
return true;
}
}
Hope this code will help you.... :)

Categories