Test only evaluating first element of array - php

I loop through the values of a form, to check that each field has 4 digits. My problem is currently it validates true or false only on the match for the first field $card1...
function cardcheck ($card1,$card2,$card3,$card4)
{
$cards = array($card1,$card2,$card3,$card4);
$regex = "/[0-9]{4}/";
for ($i=0;$i<4;$i++)
if (! preg_match ($regex,$cards[$i]))
{
return false;
}
else
{
return true;
}
}

You're returning (by using return ...) something in the first iteration every time (boolean condition with an else).
You need to put the return true outside the loop statement:
function cardcheck ($card1,$card2,$card3,$card4)
{
$cards = array($card1,$card2,$card3,$card4);
$regex = "/[0-9]{4}/";
for ($i=0;$i<4;$i++) {
if (! preg_match ($regex,$cards[$i])) {
return false;
}
}
return true;
}

function cardcheck ($card1,$card2,$card3,$card4)
{
$cards = array($card1,$card2,$card3,$card4);
$regex = "/[0-9]{4}/";
for ($i=0;$i<4;$i++)
if (! preg_match ($regex,$cards[$i]))
{
return false;
}
return true;
}

Related

find if key is in a multidimentional array

i am creating a multidimentional array and i wish to know why the following code is not working and why the other with same value when im fetching the same array is actually working.
$fruits = array(
"sale"=> array("banana", "apple", "orange"),
"regular"=> array("grapes", "pear", "ananas")
);
then in the first case it return false
1st case :
$find_price = 'sale';
if(in_array($find_price, $fruits)){
return true;
}
else {
return false;
}
and in second example i got a result of true
$find_price = 'sale';
if(isset($fruit[$find_price])){
return true;
}
else {
return false;
}
in_array() used to determine the value is in array or not. If you want to find if the key exist so array_key_exists is your friend
Look at the below snippet.
$find_price = 'sale';
if(array_key_exists($find_price, $fruits)){
return true;
}
else {
return false;
}
In your first code
$find_price = 'sale';
if(in_array($find_price, $fruits)){
return true;
}
else {
return false;
}
You use in_array(). This in_array() function the elements into the array, That element exist in array or not. And you are finding a value which is key in the array. Instead of in_array() you can use array_key_exists().
Your second code
$find_price = 'sale';
if(isset($fruit[$find_price])){
return true;
}
else {
return false;
}
You are using isset() this function tell that the element you find, is exist in code or not. Like you are finding isset($fruit[$find_price]) means isset($fruit['sale']) that is exist....
Thats why this condition is true..
You have to use loop for this type of conditions. try this.
foreach($fruits as $key => $value)
{
if($fruits[$key]['sale'])
{
return true;
}
else
{
return false;
}
}

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.

"array_key_exists()" not working properly

Code
$descriptionArr = array( "uk/page"=>"", "uk/page-two"=>"description of page 2");
function getDescription($uri){
if (array_key_exists($uri, $descriptionArr)) {
return $descriptionArr[$uri];
} else {
return false;
}
}
Situation
When i call the function with argument "uk/page-two" it returns the description
When I call the function with argument "uk/page" it returns false instead of the empty string
Issue
I would like it to return the empty string and only return false when the argument passed does not exist as key in the array.
This should work:
$descriptionArr = array( "uk/page"=>"", "uk/page-two"=>"description of page 2");
function getDescription($uri, $descriptionArr){
if (false !== array_key_exists($uri, $descriptionArr)) {
return $descriptionArr[$uri];
} else {
return false;
}
}
You can change your function to the following:
function getDescription($uri) {
if (isset($descriptionArr[$uri])) {
return $descriptionArr[$uri];
} else {
return false;
}
}

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.

Categories