user input - testing array for empty values * - php

check::empty_user()
below will test an array for 'empty' values -
NULL, FALSE, 0, or ' '
/*check*/
class check
{
static function empty_user($a)
{
return (int)!in_array('',$a);
}
}

function test_empty(array $array) {
foreach($array as $elem) {
if (!empty($elem)) return false;
}
return true; // no element, or no non-empty element
}

in_array('', $array);
I think that is what you're after?

Your function isn't going to test anything other than the first element of your array. Return causes the function to cease execution.
PHP has empty and isset functions, either of those should be suitable testing array elements. To test the entire array you can use in_array and look for empty values. However you'll have to implement your own method for processing nested arrays.

You test empty could also be the folowing:
// if the array has at least one empty value
function test_empty(array $array) {
foreach($array as $elem) {
if (empty($elem)) return true;
}
return false;
}

In summary use
empty() or in_array()
and make note that:
$value=='' tests for null, false, 0, and ''

Related

How to check in PHP that any values exist in array in addition to some fixed value

I have an array like this:
$array = array('static_value_1', 'static_value_2', 'extra_value_1', 'extra_value_2');
How could I return true if any value exists in array in addition to static_value_1 and/or static_value_2?
For example this array should return true:
array = array('static_value_1', 'static_value_2', 'extra_value_1');
and this one false:
array = array('static_value_1', 'static_value_2');
Thanks!
I think just looping looking for non-static should work:
function check_array($check) {
$static=Array('static_value_1', 'static_value_2');
// Dealing with empty array.
if(count($check)==0) return false;
foreach($check as $value) {
// If value is not in static collection is an addition...
if(!in_array($value, $static)) {
return false;
}
}
return true;
}

Shorthand for checking if associative array not null and if key exists

Is there any way of checking if a variable is not null and then to check if variable has nested associative array keys using a shorthand? Something like optional chaining for associative arrays?
Example of what I would like to make concise:
public $arr;
//$arr gets set as an associative array somewhere else in the code.
function someFunc() {
if ($this->arr && $this->arr['key1'] && $this->arr['key1']['key2'] == 'Some Value') { // shorten this line?
// Do Something Cool!
}
}
I am looking for something similar to Optional Chaining in Javascript e.g. :
if (obj.key1?.key2 == 'Some Value') {
// Do something kool
}
There is a high probability that this is a duplicate and I apologize in advance if that is the case. I tried searching for this for associative arrays and could not find anything specific.
You could keep the if statement intact, but replace $this->arr && $this->arr['key1'] with an Null Coalescing Operator (??), so if those aren't defined, it will use the fallback, that isn't equal to the test string:
if (($this->arr['key1']['key2'] ?? false) == 'Some Value') {
// Do Something Cool!
}
So if $this->arr['key1']['key2'] is defined, you'll compare that to Some Value, otherwise, if it's not defined, you'll compare (eg) false to Some Value witch will remain false.
Use the php function isset: https://www.php.net/manual/en/function.isset.php
It will check for multiple keys: if( isset($this->arr['key1']['key2'] ) {...} and also includes a null check.
If you for some reason need to shorten it even more, simply decompose it to another function:
public $arr;
//$arr gets set as an associative array somewhere else in the code.
function someFunc()
{
if ($this->checkForSomeValue($this->arr, 'Some Value', 'key1', 'key2')) { // shorten this line?
// Do Something Cool!
}
}
function checkForSomeValue(array $arr, string $valueToCheck, ...$keys)
{
$valueCompare = $arr;
foreach($keys as $key)
{
if(!isset($valueCompare[$key]))
{
$valueCompare = null;
break;
}
else
{
$valueCompare = $valueCompare[$key];
}
}
return $valueCompare && $valueCompare === $valueToCheck;
}
I've updated the answer to allow supplying keys

Why this function always returning false?

I have a very basic question. It's may very poor question but I just want to clear my confusion.
function check_array($user_value,$array)
{
foreach ($array as $key => $value) {
if($value==$user_value)
{
return true;
}
return false;
}
//return false;
}
Why this function always returning false.
for example If I have $numbers = array(1,2,3). If I match 2 with this array it should return me true else return me false. But why it's returning always false ?
why it's returning always false ?
Try to "execute" this function yourself acting as a computer.
If the first element of array is equal to $user_value, it will return true. If not - it will move futher down the loop and return false.
Probably, you wanted to check all the elements of array for equality. In this case you need to use this:
function check_array($user_value,$array)
{
foreach ($array as $key => $value) {
if($value==$user_value)
{
return true;
}
}
return false;
}
The return false is in the wrong place, it should be where you commented it out but not in the other place it is.
function check_array($user_value,$array)
{
foreach ($array as $key => $value) {
if($value==$user_value)
{
return true;
}
}
return false;
}
If the return is in the other place, it will return false after failing to find your value in the first array cell.
You dont need to create a function for it when php has already have it in_array
you can use it like in a single line
$result = in_array($user_value,$array)
It will return true if the value is found and false if not found.
You need not to loop through the array
You have the return false inside of the loop. That means if the first element isn't a match, it will return false. It won't even check the second element of your array
Your function will be returning false, unless it matches the first value in the array.
This is because at the moment your logic is in the wrong order, and if the first value in the array doesn't match $user_value the function returns false.
You could solve this problem by moving the return false; line of code below the loop.
Now the loop will run through all the values in the array. It will return true if it matches one, and if it has checked all the values and there is no match then it will then return false.
function check_array($user_value,$array)
{
foreach ($array as $key => $value) {
if($value==$user_value) return true;
}
return false;
}
This should clear up the logic mistake in your code. However I up-voted Veerendra's in_array() answer as that means there is no need for any loop, cutting down your code.

Find an Object in an array by comparing Object->value to all Object->values in array PHP

So my array contains objects like this:
$arr = array(
new Card('10', 'Spades'),
new Card('Jack', 'Diamonds'),
new Card('King', 'Spades')
);
Now I have a function:
function hasCard(Card $card) {
if (in_array($card, $arr)) return true;
return false;
}
Now above does not really work since I need to compare ($card->rank == $arr[$x]->rank) for each element in that $arr without looping. Is there a function on PHP that allows you to modify the compareTo method of array_search?
I'd suggest using array_filter here. (Note: make sure $arr is available inside the hasCard function)
function hasCard(Card $card) {
$inArray = array_filter($arr, function($x) use($card){
return $x->rank === $card->rank;
});
return count($inArray) > 0;
}
DEMO: https://eval.in/166460
The $arr variable is not going to be available within the function hasCard, unless you pass it as a parameter.
To answer your question, look at array_filter. This will get you a callable function in which you can pass the $arr and $card as parameters.

Passing location in subarray as string

I have a function that searches a multidimensional array for a key, and returns the path
inside the array to my desired key as a string.
Is there any way I can use this string in php to reach this place in my original array, not to get to the value but to make changes to this specific bracnch of the array?
An example:
$array = array('first_level'=>array(
'second_level'=>array(
'desired_key'=>'value')));
in this example the function will return the string:
'first_level=>second_level=>desired_key'
Is there a way to use this output, or format it differently in order to use it in the following or a similar way?
$res = find_deep_key($array,'needle');
$array[$res]['newkey'] = 'injected value';
Thanks
If the keys path is safe (e.g. not given by the user), you can use eval and do something like:
$k = 'first_level=>second_level=>desired_key';
$k = explode('=>', $k);
$keys = '[\'' . implode('\'][\'', $k) . '\']';
eval('$key = &$array' . $keys . ';');
var_dump($key);
I think you want to do a recursive search in the array for your key? Correct me if i am wrong.
Try this
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
Taken from here http://in3.php.net/manual/en/function.array-search.php#91365
You need something like:
find_key_in_array($key, $array, function($foundValue){
// do stuff here with found value, e.g.
return $foundValue * 2;
});
and the implementation would be something like:
function find_key_in_array($key, $array, $callback){
// iterate over array fields recursively till you find desired field, then:
...
$array[$key] = $callback($array[$key]);
}
If you need to append some new sub-array into multidimensional complex array and you know where exactly it should be appended (you have path as a string), this might work (another approach without eval()):
function append_to_subarray_by_path($newkey, $newvalue, $path, $pathDelimiter, &$array) {
$destinationArray = &$array;
foreach (explode($pathDelimiter, $path) as $key) {
if (isset($destinationArray[$key])) {
$destinationArray = &$destinationArray[$key];
} else {
$destinationArray[$newkey] = $newvalue;
}
}
}
$res = find_deep_key($array,'needle');
append_to_subarray_by_path('newkey', 'injected value', $res, '=>', $array);
Of course, it will work only if all keys in path already exist. Otherwise it will append new sub-array into wrong place.
just write a function that takes the string and the array. The function will take the key for each array level and then returns the found object.
such as:
void object FindArray(Array[] array,String key)
{
if(key.Length == 0) return array;
var currentKey = key.Split('=>')[0];
return FindArray(array[currentKey], key.Remove(currentKey));
}

Categories