function to check POST multidimensional array - php

I have the following function to check the array's keys
public function check($arr, $key, $default = NULL) {
return isset($arr[$key]) && !empty($arr[$key]) ? $arr[$key] : $default;
}
$this->check($info, 'location'); //it's working
$this->check($info['birthday'], 'year'); //it's working
$this->check($_POST, 'email'); //it's working
$this->check($_POST, 'password'); //it's working
everything is ok until multidimensional array appears
Notice: Array to string conversion in

change your function code to:
public function check($arr, $key, $default = NULL) {
return isset($arr[$key]) ? $arr[$key] : $default;
}
if you still want to check for empty value (though isset is enough):
public function check($arr, $key, $default = NULL) {
return isset($arr[$key]) && (!empty($arr[$key]) || is_array($arr[$key])) ? $arr[$key] : $default;
}

Not 100% sure what are you looking for but please notice that if you have email[][] field, when you return $arr[$key] you are returning an array. So you have to check if $arr[$key] is an array before returning its value.
public function check($arr, $key, $default = NULL) {
if( isset($arr[$key]) && !empty($arr[$key]) || is_array($arr[$key])) {
if(is_array($arr[$key])) {
//apply here your second level check condition
} else return $arr[$key]; // returns its value (if it's not an array)
} else return $default;
}
Hope it helps
Instead, if you're trying to build a function checking recursively if $key is contained somewhere in a multidimensional array, you have to do otherwise (that's why I wrote I'm not 100% sure what you're looking for)

? $arr[$key]
In the above code you are using $_POST['email'] (which is an array) as a string.

Related

Operator "===" doesn't evaluate correctly when used in an object as it should php

I am trying to loop through an array assigned to an object. The function entity_products_check() must compare the submitted product to an array of pre-held values from a database.
The foreach loop must evaluate to true in the provided test example. However, for reasons I cannot understand the === operator returns empty (i.e. null) and XAMPP evaluates it to false. For some bizarre reason this occurs only if one checks for the first value. For any other result it executes correctly.
I do not understand why this happens?
$entity=array("products"=>array("machine", "lollipop"));
class Borrowing_Cost
{
public array $entity;
public array $item;
public array $borrowing;
public function __construct($entity, $item, $borrowing)
{
$this->entity = $entity;
$this->item = $item;
$this->borrowing = $borrowing;
}
public function entity_products_check($arg){
$is_item = "";
**foreach ($this->entity["products"] as $value){
if($value === $arg){
$is_item = "true";
} else {
$is_item = "false";
}
}**
return $is_item;
}
}
$borr = new Borrowing_Cost($entity, $item, $borrowing);
echo $borr->entity_products_check("machine") . "<br>";
In your code you compare every item against the value you are looking for, so after it finds it, it will still go onto the next item and set the flag to false.
This code sets to false at the start and only ever flags it true when found and then stops...
public function entity_products_check($arg){
$is_item = "false";
foreach ($this->entity["products"] as $value){
if($value === $arg){
$is_item = "true";
break;
}
}
return $is_item;
}
Or you could use in_array() to check if the value is in the array for you...
public function entity_products_check($arg){
return in_array($arg, $this->entity["products"])
? "true" : "false";
}

Check if all elements of array equal to something

Have
$my_arr_1 = array ("denied","denied","denied");
$my_arr_2 = array ("denied","denied","allowed");
Need a func that would check if all elements in the array equal to something:
in_array_all("denied",$my_arr_1); // => true
in_array_all("denied",$my_arr_2); // => false
Is there a php native function like in_array_all?
If not, what would be the most elegant way to write such a func?
function in_array_all($value, $array)
{
return (reset($array) == $value && count(array_unique($array)) == 1);
}
function in_array_all($needle,$haystack){
if(empty($needle) || empty($haystack)){
return false;
}
foreach($haystack as $k=>$v){
if($v != $needle){
return false;
}
}
return true;
}
And if you wanted to get really crazy:
function in_array_all($needle,$haystack){
if(empty($needle)){
throw new InvalidArgumentException("$needle must be a non-empty string. ".gettype($needle)." given.");
}
if(empty($haystack) || !is_array($haystack)){
throw new InvalidArgumentException("$haystack must be a non-empty array. ".gettype($haystack)." given.");
}
foreach($haystack as $k=>$v){
if($v != $needle){
return false;
}
}
return true;
}
I don't know the context of your code. But what about reversing the logic? Then you are able to use PHP's native function in_array.
$my_arr_1 = array ("denied","denied","denied");
$my_arr_2 = array ("denied","denied","allowed");
!in_array("allowed", $my_arr_1); // => true
!in_array("allowed", $my_arr_2); // => false
This entirely depends on your data set of course. But given the sample data, this would work. (Also, notice the negation ! in front of each method call to produce the desired boolean result).
Another solution using array_count_values():
function in_array_all(array $haystack, $needle) {
$count_map = array_count_values($haystack);
// in your case: [ 'denied' => 2, 'allowed' => 1 ]
return isset($count_map[$needle]) && $count_map[$needle] == count($haystack);
}
Richard's solution is best but does not have one closing paren ;-) - here is fixed and abridged:
function in_array_all($needle,$haystack)
{
if( empty($needle) || empty($haystack) ) return false;
foreach($haystack as $v)
{
if($v != $needle) return false;
}
return true;
}

php null replacement function

there is this function called Nz() in visual basic for application. the function checks variable nullity and returns a provided value if it finds the variable is null.
i try to write the same function in php, which looks like below:
function replace_null($value, $replace) {
if (!isset($value)) {
return $replace;
} else {
return $value;
}
}
$address = replace_null($data['address'], 'Address is not available.');
of course, if $data['address'] is found null, php will stop executing the code and replace_null won't be called.
i'm currently using ternary
(isset(data['address']) ? data['address'] : 'Address is not available.');
but i think replace_null, if it works, will offer a more convenient way.
is there a function in php that provide the same functionality as vba's Nz()?
any suggestion will be appreciated.
thanks in advance.
A bit roundabout: If you only use this to check for array members, you could pass the key separately:
function get_with_default($arr, $key, $defval)
{
return isset($arr[$key]) ? $arr[$key] : $defval;
}
If the variable could be set but null (Edit: which it cannot, thanks #deceze), add another check:
function get_and_coalesce_with_default($arr, $key, $defval)
{
return (isset($arr[$key]) && !is_null($arr[$key]) ? $arr[$key] : $defval;
}
As pointed out, isset() only succeeds on non-null values, so the above doesn't add anything. We can write a non-trivial check with array_key_exists, though:
function get_with_default_v2($arr, $key, $defval)
{
return (array_key_exists($key, $arr) && !is_null($arr[$key]) ? $arr[$key] : $defval;
}
You could pass the array and the key separately like this:
function valueOrDefault($array, $key, $default) {
return isset($array[$key]) ? $array[$key] : $default;
}
$address = valueOrDefault($data, 'address', 'Address is not available.');
If you pass by reference, PHP won't error out:
function Nz(&$var, $def='') {
return isset($var) ? $var : $def;
}
http://php.net/manual/en/language.references.pass.php
If the variable is declared you do something like $value?:$replace
function replace_null($value='', $replace='') {
if (!isset($value)) {
return $replace;
} else {
return $value;
}
}
Try this. It will allow you to call the function with or without passing parameters.
<?
function replace_null($value, $replace) {
if(empty($value) && $value !== '0') {
return $replace;
} else {
return $value;
}
}
$address = replace_null("0", "replacing null");
echo $address;
?>
I think using the is_null function would be much more useful:
$address = $data['address'];
if ( is_null($address) ) $address = 'Address is not available.';
If you really want this as a function:
function replace_null($value, $replace) {
if (is_null($value)) return $replace;
return $value;
}
$address = replace_null($data['address'], 'Address is not available.');

PHP Make a simple if-isset-empty function

I'm coding a worksheet app for a printer company.
I'm getting flood of forms.
For every single input field I have to check if the $_POST variables are set, and if, so echo back the value. (In case of some error, for example after a validation error, the user shouldn't retype the whole form)
Sample code:
if(isset($_POST['time'])&&!empty($_POST['time'])){echo $_POST['time'];}
I had to implement this about a hundred times.
So I tried to figure out some kind of function to make this simple and readable.
Something like this:
function if_post_echo($key, $default = "") {
if(isset($_POST[$key])&&!empty($_POST[$key])){
echo $_POST[$key];
}else{
echo $default;
}
}
But this wont work.
I have tried to pass in the $_POST for the $key variable like this:
if_post_echo($_POST['time'])
function if_request_echo($key, $default = "") {
if(isset($key)&&!empty($key)){
echo $key;
}else{
echo $default;
}
}
And I also tried this:
function if_request_echo($key, $default = null) {
return isset($_REQUEST[$key])&&!empty($_REQUEST[$key]) ? $_REQUEST[$key] : $default;
}
Without any reasonable outcome.
The question:
How can I forge a function that looks for the necessary $_POST variable and returns it or if its unset then returns an empty string.
And is there a way to do this for $_GET and $_REQUEST, too? (Or simply duplicate?)
Your PHP testing function:
<?php
function test_req($key, $default = '') {
if(isset($_REQUEST[$key]) and
!empty($_REQUEST[$key])) {
return $_REQUEST[$key];
} else {
return $default;
}
}
?>
Then in your form HTML:
<input name="my_field" value="<?php echo htmlentities(test_req('my_field')); ?>" />
$_REQUEST (linked) is a PHP super global that contains both POST ($_POST) and GET ($_GET) request parameters.
If you only want to capture POST request parameters then it would be:
<?php
function test_req($key, $default = '') {
if(isset($_POST[$key]) and
!empty($_POST[$key])) {
return $_POST[$key];
} else {
return $default;
}
}
?>
For example.
If you have a large amount of fields, I would propose that you also use an array of defaults:
$defaults = array(
"time" => "default",
"name" => "enter name here",
"text..." => "...",
);
$fields = array_filter($_POST) + $defaults;
$fields will then contain a list of form values with either the POST data or a preset default. No isset, see?
array_filter man page particularly: If no callback is supplied, all entries of input equal to FALSE will be removed. Goes some way to explaining the working behind this solution.
This should work:
function if_post_echo($key, $default = ''){
if(isset($_POST[$key]) AND !empty($_POST[$key]){
echo $_POST[$key];
}
echo $default;
}
If you're having problems I recommend that you try var_dump($_POST) or print_r($_POST) to see if everything has been properly posted.
Just to note, this is redundant:
isset($_POST[$key]) && !empty($_POST[$key])
An unset variable is going to always be "empty", so isset() is implied in your empty() call.
For your logic you can achieve the same result with just:
!empty($_POST[$key])
Your first function works perfectly to me.
Why do you think it doesn't work?
However, a better variant would be
function _post($key, $default = "") {
if(isset($_POST[$key])){
return $_POST[$key];
}else{
return $default;
}
}
To use it :
echo $_post($key); // You could define the message as a second parameter.
function requireArray( $array, $required ) {
foreach( $required as $k=>$v ) {
if ( !isset($array[$k]) || empty($array[$k]) )
return false;
}
return true;
}
#call like this:
requireArray($_POST, array('time', 'username', 'foo'));
If you want to know specifically:
function missingFrom( $array, $required ) {
$r = array();
foreach( $required as $k ) {
if ( !isset($array[$k]) || empty($array[$k]) )
$r[] = $k;
}
return $r;
}
Called like previous function.
Your method seems to work fine here:
function if_post_echo($key, $default = "") {
if(isset($_POST[$key])&&!empty($_POST[$key])){
echo $_POST[$key];
}else{
echo $default;
}
}
I made a simple input with the name test and the form method is POST and using echo if_post_echo('test');.
It posted on the page what was in the text box.
This feature is being added in PHP 7 as the "Null Coalesce Operator" using two question marks:
echo ($_GET['message'] ?? 'default-if-not-set');
https://wiki.php.net/rfc/isset_ternary

What is a good strategy for safely reading values out of a PHP array?

I'm trying to read values from $_SESSION which may or may not be set, while avoiding undefined index warnings. I'm used to Python dicts, which have a d.get('key','default') method, which returns a default parameter if not found. I've resorted to this:
function array_get($a, $key, $default=NULL)
{
if (isset($a) and isset($a[$key]))
return $a[$key];
else
return $default;
}
$foo = array_get($_SESSION, 'foo');
if (!$foo) {
// Do some foo initialization
}
Is there a better way to implement this strategy?
I would use array_key_exists instead of isset for the second condition. Isset will return false if $a[$key] === null which is problematic if you've intentionally set $a[$key] = null. Of course, this isn't a huge deal unless you set a $default value to something other than NULL.
function array_get($a, $key, $default=NULL)
{
if (isset($a) and array_key_exists($key, $a))
return $a[$key];
else
return $default;
}
$foo = (isset($_SESSION['foo'])) ? $_SESSION['foo'] : NULL;

Categories