PHP checking if all inputs were set doesn't function? - php

So I started using MVC. I don't use a framework. It's just self-practice.
So this is my register part:
protected function _instance()
{
if ($_POST != null)
{
/**
* Validating if forms are not empty
**/
if (self::validateForms())
{
echo 1;
}
else
{
new Error("One of the forums was empty..");
}
}
}
private static function validateForms()
{
$inputs = array (
'username', 'password', 'repassword',
'email', 'password_f', 'repassword_f',
'display'
);
$i = 0;
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}
}
}
}
Now it only must check if inputs were set, if not, throw error.
But it seems like it doesn't work as it always runs that error.
$i must grow everytime a input was full, but I don't think it does.
When I do echo $i, it only echoing "1".
Why is it only looping through it once?

The problem is you are returning within your loop after the first test.
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}
}
}
should be
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
}
}
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}
or more concisely
foreach ($inputs as $key)
{
if (!isset($_POST[$key]) || empty($_POST[$key]))
{
return false;
}
}
return true;

You need to take the checking of $i out of the loop so that it checks how many were actually set once all the inputs have been cycled through. Otherwise, it is checking on the first time, seeing that it is not equal and returning false.
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
}
}
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}

Related

preg_match - For sure there is a better way to search for these characters

So, I want to check the users-input, if it contains some of these characters:
" ' < >
I hope someone can show me a better way with less code
Thanks!
I used preg_match, but i just managed it with 4 nested if's.
/*Checks if the given value is valid*/
private function checkValidInput($input)
{
/*If there is no " */
if(preg_match('/"/', $input) == false)
{
/*If there is no ' */
if(preg_match("/'/", $input) == false)
{
/*If there is no <*/
if(preg_match("/</", $input) == false)
{
/*If there is no >*/
if(preg_match("/>/", $input) == false)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
You could create a regex class
preg_match('#["\'<>]#', $input);
Edit:
If you need to check for all characters then use strpos() with for loop
function checkInput($val) {
$contains = true;
$required = "<>a";
for($i = 0, $count = strlen($required); $i < $count ; ++$i) {
$contains = $contains && false !== strpos($val, $required[$i]);
}
return $contains;
}
var_dump(checkInput('abcd<>a')); // true
var_dump(checkInput('abcd>a')); // false, doesn't contain <

PHP: check if an element belongs to an array

I know PHP 4 and PHP 5 supports a built in function in_array for determining is an element is in an array or not.
But, I am using a prior version of PHP for some reason and wanted to know what is the alternative for it.
Use a custom function. For future compatibility, you could use function_exists to check if the current version of PHP that you're using does indeed have in_array.
function inArray($needle, $haystack)
{
if (function_exists('in_array')) {
return in_array($needle, $haystack);
} else {
foreach ($haystack as $e) {
if ($e === $needle) {
return true;
}
}
return false;
}
}
If you are using something older than PHP 4, foreach will also be unavailable, so you will need to stick with list and each. Also to make in forward compatible, use third parameter for strict comparison:
if (!function_exists('in_array')) {
function in_array($needle, $haystack, $strict = false) {
while (list($key, $item) = each($haystack)) {
if ($strict && $needle === $item) {
return true;
} else if (!$strict && $needle == $item) {
return true;
}
}
return false;
}
}
Without checking what functions were available in what versions, and comparing against the version you are using (we're not php.net encyclopedia's), your best bet is to go back to basics, and just loop through and check.
function in_array($val, $array) {
foreach($array as $a) {
if($a === $val)
return true;
}
return false;
}
You can create your own function to mimic the functionality with
function my_in_array($ar, $val)
{
foreach($ar as $k => $v)
{
if($v == $val) return true;
}
return false;
}
or if you looking for a key
function my_in_array($ar, $val)
{
foreach($ar as $k => $v)
{
if($k == $val) return true;
}
return false;
}
Create your own in array function something like below:
function my_in_array($value, $arr) {
foreach ($arr as $a) {
if ($a == $value) {
return true;
}
}
return false;
}

Remove duplicate values on an array with a condition in PHP

I want to remove some duplicate values on an array, but there is a condition that the script has to ignore the array that contains a specific word.
Below code is adapted from PHP: in_array.
$array = array( 'STK0000100001',
'STK0000100002',
'STK0000100001', //--> This should be remove
'STK0000100001-XXXX', //--> This should be ignored
'STK0000100001-XXXX' ); //--> This should be ignored
$ignore_values = array('-XXXX');
if(make_unique($array, $ignore_values) > 0) {
//ERROR HERE
}
The function to make the array unique is:
function make_unique($array, $ignore) {
$i = 0;
while($values = each($array)) {
if(!in_array($values[1], $ignore)) {
$dupes = array_keys($array, $values[1]);
unset($dupes[0]);
foreach($dupes as $rmv) {
$i++;
}
}
}
return $i;
}
I have tried to use if(!in_array(str_split($values[1]), $ignore)) ... but it just the same.
The array should become like:
STK0000100001
STK0000100002
STK0000100001-XXXX
STK0000100001-XXXX
How to do that?
Try this one, just remove the print_r(); inside the function when using in production
if(make_unique($array, $ignore_values) > 0) {
//ERROR HERE
}
function make_unique($array, $ignore) {
$array_hold = $array;
$ignore_val = array();
$i = 0;
foreach($array as $arr) {
foreach($ignore as $ign) {
if(strpos($arr, $ign)) {
array_push( $ignore_val, $arr);
unset($array_hold[$i]);
break;
}
}
$i++;
}
$unique_one = (array_unique($array_hold));
$unique_one = array_merge($unique_one,$ignore_val);
print_r($unique_one);
return count($array) - count($unique_one);
}
This should work for >= PHP 5.3.
$res = array_reduce($array, function ($res, $val) use ($ignore_values) {
$can_ignore = false;
foreach ($ignore_values as $ignore_val) {
if (substr($val, 0 - strlen($ignore_val)) == $ignore_val) {
$can_ignore = true;
break;
}
}
if ( $can_ignore || ! in_array($val, $res)) {
$res[] = $val;
}
return $res;
}, array()
);
Otherwise
$num_of_duplicates = 0;
$res = array();
foreach ($array as $val) {
$can_ignore = false;
foreach ($ignore_values as $ignore_val) {
if (substr($val, 0 - strlen($ignore_val)) == $ignore_val) {
$num_of_duplicates++;
$can_ignore = true;
break;
}
}
if ( $can_ignore || ! in_array($val, $res)) {
$res[] = $val;
}
}
Edit: Added duplicate count to the second snippet.

PHP function to check if the number belongs to the interval

There is an array:
$bounds = array([0]=>array('lower'=>2,'upper'=>5),
[1]=>array('lower'=>0,'upper'=>3));
and a variable:
$val = 4;
Is there any PHP function that can say whether $val belongs to any interval defined by 'lower' and 'upper' bounds in $bounds array? In this example 4 belongs to the 1st interval [2; 5]. So, the answer should be 'true'.
I don't think there is a built-in function to do this.
However, you can do it with a foreach statement:
function check_interval($bounds, $val) {
foreach ($bounds as $array) {
if($array['lower'] <= $val && $array['upper'] >= $val)
return true;
}
return false;
}
I'm not aware of any. You'll probably have to code it. Something like this will do:
function isFromInterval($bounds, $val) {
foreach ($bounds as $value) {
if ($val >= $value['lower'] && $val <= $value['upper']) {
return true;
}
}
return false;
}
No.
You would have to make a loop for the array like this
$val = 4;
$key_id = FALSE;
foreach($bounds as $key => $data){
if($val <= $data['upper'] AND $val >= $data['lower']){
$key_id = $key;
break;
}
}
if($key_id !== FALSE){
// found something
// $bounds[$key_id] is your result in the array
} else {
// found nothing
}
As a function
function find_range($bounds=array(), $val=0, $return_key=TRUE){
if(is_array($bounds) === FALSE){
$bounds = array();
}
if(is_numeric($val) === FALSE){
$val = 0;
}
if(is_bool($return_key) === FALSE){
$return_key = TRUE;
}
$key_id = FALSE;
foreach($bounds as $key => $data){
if($val < $data['upper'] AND $val > $data['lower']){
$key_id = $key;
break;
}
}
if($key_id !== FALSE){
return ($return_key === TRUE ? $key_id : TRUE);
} else {
return FALSE;
}
}
No, but you can do:
$bounds = array(3=>array('lower'=>2,'upper'=>5),
4=>array('lower'=>0,'upper'=>3));
$val = 4;
foreach($bounds as $num => $bound){
if(max($bound) >= $val && $val >= min($bound)){
echo $num;
}
}

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