I want to generate a dynamic condition with values in the array $unique_keys
$unique_keys = array('name', 'phone');
And the result in PHP will be :
if($search_array['name'] == $current_array['name'] && $search_array['phone'] == $current_array['phone']){
// some code
}
The only way i know it's a foreach and an eval, but there's no cleaner way, something likes Variable variables ?
Why you need eval or variable variables? You can use just key names.
$unique_keys = array('name', 'phone');
...
$good = true;
foreach ($unique_keys as $k) {
if ($search_array[$k] != $current_array[$k]) {
$good = false;
break;
}
}
if ($good) {
// Found!
} else {
// No luck
}
Related
I have array as follows,
$arr['fixed_key'][0]['key1']['key2'] = 'y';
$arr['fixed_key'][1]['key1']['key2'] = 'y';
$arr['fixed_key'][2]['key1']['key2'] = 'n';
$arr['fixed_key'][3]['key1']['key2'] = 'n';
I want to remove all arrays which have key2='n', I can traverse through array in a loop and achieve this, as follows:
$l=length($arr);
for($i=0;$i<$l;$i++) {
if($arr['fixed_key'][$i]['key1']['key2'] == 'n') {
unset($arr['fixed_key'][$i]['key1']['key2']);
}
}
My question is, is it possible to do this in better way, like array_map or array_walk, what is the best possible way?
You can use array_filter
$arr['fixed_key'][0]['key1']['key2'] = 'y';
$arr['fixed_key'][1]['key1']['key2'] = 'y';
$arr['fixed_key'][2]['key1']['key2'] = 'n';
$arr['fixed_key'][3]['key1']['key2'] = 'n';
$filtered = array_filter($arr['fixed_key'], function ($val) { return $val['key1']['key2'] !== "n"; });
We can achive by using array_search() and unset, try the following:
if(($key = array_search($del_value, $arr)) !== false) {
unset($arr[$key]);
}
In my page, there are multiple $_GET values. ie
if(isset($_GET["projects"]))
{ ..... }
else if(isset($_GET["research"]))
{ ...... }
else if(isset($_GET["publication"]))
{ ..... }
...upto 10 elseif's
Can I shorten this?
Can I get these values {projects,research, publication,..} in a variable.?
Ok so I guess I figured out what you want from your comments. Lets see.
$types = array('projects', 'research', 'publication'); // add as many as you want
$valid = array_intersect_key($_GET, array_flip($types));
if (count($valid) > 1)
die "More than one category is set, this is invalid.";
if (!$valid)
die "No category was set, you must choose one.";
foreach ($valid as $type => $value) // just to split this one element array key/value into distinct variables
{
$value = mysql_real_escape_string($value); // assuming you are using mysql_*
$sql = "SELECT * FROM table WHERE $type = '$value'";
}
...
Yes, you can assign these in a variable -
if(isset($_GET["projects"]))
{
$value = $_GET['projects'];
}
else if(isset($_GET["research"]))
{
$value = $_GET['research'];
}
else if(isset($_GET["publication"]))
{
$value = $_GET['publication'];
}
echo $value;
I'm guessing you're expecting a single value in $_GET, like ?projects=foo or ?research=bar. In that case:
$type = key($_GET);
$value = $_GET[$type];
echo "$type = $value";
$projects = $_GET["projects"];
Or just use directly from $_GET, this is an associative array with all the values.
foreach ($_GET as $key => $value){
if(!empty($value)){
$type = $key; //if you expect a single item
$type[] = $key; //if you expect multiple items
}
}
if the intent is to check if values on a form have been answered/filled out you could use
if(isset($_GET['project'] || ... || isset($_GET['publication'])
{
// Insert Code Here
}
else
{
// Insert Code Here
}
The above code is assuming the fields are not text fields or textareas if those are the types of inputs then instead of
if(isset($_GET['project']))
use
if($_GET['project'] != "")
I didn't completely understood what you are saying but looks like that you are trying to execute something when all $_GET is true. If so then use the code below
if(isset($_GET["projects"]) && isset($_GET["research"]) && isset($_GET["publication"]) )
{ ..... }
Hope this helps you
If I have an array:
$nav = array($nav_1, $nav_2, $nav_3);
and want to check if they are empty with a loop (the real array is much bigger), so that it checks each variable separately, how do I do it?
I want something like this;
$count = 0;
while(count < 3){
if(empty($nav[$count])) //the loops should go through each value (nav[0], nav[1] etc.)
//do something
$count = $count+1;
}else{
//do something
$count = $count+1;
}
}
Pretty straight-forward with a foreach loop:
$count = 0;
foreach ($nav as $value) {
if (empty($value)) {
// empty
$count++;
} else {
// not empty
}
}
echo 'There were total ', $count, ' empty elements';
If you're trying to check if all the values are empty, then use array_filter():
if (!array_filter($nav)) {
// all values are empty
}
With the following code you can check if all variables are empty in your array. Is this what you are looking for?
$eachVarEmpty = true;
foreach($nav as $item){
// if not empty set $eachVarEmpty to false and go break of the loop
if(!empty(trim($item))){
$eachVarEmpty = false;
// go out the loop
break;
}
}
$empty = array_reduce($array, function(&$a,$b){return $a &= empty($b);},true);
I need to check if $_POST variables exist using single statement isset.
if (isset$_POST['name'] && isset$_POST['number'] && isset$_POST['address'] && etc ....)
is there any easy way to achieve this?
Use simple way with array_diff and array_keys
$check_array = array('key1', 'key2', 'key3');
if (!array_diff($check_array, array_keys($_POST)))
echo 'all exists';
$variables = array('name', 'number', 'address');
foreach($variables as $variable_name){
if(isset($_POST[$variable_name])){
echo 'Variable: '.$variable_name.' is set<br/>';
}else{
echo 'Variable: '.$variable_name.' is NOT set<br/>';
}
}
Or, Iterate through each $_POST key/pair
foreach($_POST as $key => $value){
if(isset($value)){
echo 'Variable: '.$key.' is set to '.$value.'<br/>';
}else{
echo 'Variable: '.$key.' is NOT set<br/>';
}
}
The last way is probably your easiest way - if any of your $_POST variables change you don't need to update an array with the new names.
Do you need the condition to be met if any of them are set or all?
foreach ($_POST as $var){
if (isset($var)) {
}
}
$variableToCheck = array('key1', 'key2', 'key3');
foreach($_POST AS $key => $value)
{
if( in_array($key, $variableToCheck))
{
if(isset($_POST[$key])){
// get value
}else{
// set validation error
}
}
}
That you are asking is exactly what is in isset page
isset($_POST['name']) && isset($_POST['number']) && isset($_POST['address'])
is the same as:
isset($_POST['name'], $_POST['number'], $_POST['address'])
If you are asking for a better or practical way to assert this considering that you already have all the required keys then you can use something like:
$requiredKeys = ['name', 'number', 'address'];
$notInPost = array_filter($requiredKeys, function ($key) {
return ! isset($_POST[$key]);
});
Remember, isset does not return the same result as array_key_exists
The following is a custom function that take an array for the required posted elements as a parameter and return true if they all posted and there is no any of them is empty string '' or false if there is at least one of them is not:
function checkPosts($posts){
if (!is_array($posts)) return "Error: Invalid argument, it should be an array";
foreach ($posts as $post){
if (!isset($_POST[$post]) || $_POST[$post] == '') return false;
}
return true;
}
// The structure of the argument array may be something like:
$myPosts = array('username', 'password', 'address', 'salary');
Use Array to collect data from form as follow:
PersonArray['name],
PersonArray['address],
PersonArray['email], etc.
and process your form on post as below:
if(isset($_POST['name'])){
...
}
Old post but always useful
foreach ($_POST as $key => $val){
$$key = isset($_POST[$key]) ? $_POST[$key] : '';
}
Use simple way with in_array and array_keys
$check_array = array('key1', 'key2', 'key3');
if(in_array(array_keys($_POST), $check_array)) {
echo 'all exists';
}
Note that the name of the submit button must be included in the array too.
if isset(($_POST['name']) && ($_POST['number']) && ($_POST['address']))
You can also use this. it might be more easy.
I have a form that passes something like in a URL
?choice=selection+A&choice=selection+C
I'm collecting it in a form with something like (I remember that $_GET is any array)
$temp = $_GET["choice"];
print_r($temp);
I'm only getting the last instance "selection C". What am I missing
I am assuming 'choice' is some kind of multi-select or checkbox group? If so, change its name in your html to 'choice[]'. $_GET['choice'] will then be an array of the selections the user made.
If you don't intend to edit the HTML, this will allow you to do what you're looking to do; it will populate the $_REQUEST superglobal and overwrite its contents.
This assumes PHP Version 5.3, because it uses the Ternary Shortcut Operator. This can be removed.
$rawget = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : false;
$rawpost = file_get_contents('php://input') ?: false;
$target = $rawget;
$_REQUEST = array();
if ($target !== false) {
$pairs = explode('&',$rawget);
foreach($pairs as $pair) {
$p = strpos($pair,'=');
if ($p === false && !empty($pair)) {
$_REQUEST[$pair] = null;
}
elseif ($p === 0 || empty($pair)) {
continue;
}
else {
list($name, $value) = explode('=',$pair,2);
$name = preg_replace('/\[.*\]/','',urldecode($name));
$value = urldecode($value);
if (array_key_exists($name, $_REQUEST)) {
if (is_array($_REQUEST[$name])) {
$_REQUEST[$name][] = $value;
}
else {
$_REQUEST[$name] = array($_REQUEST[$name], $value);
}
}
else {
$_REQUEST[$name] = $value;
}
}
}
}
As it stands, this will only process the QueryString/GET variables; to process post as well, change the 3rd line to something like
$target = ($rawget ?: '') . '&' . ($rawpost ?: '');
All that having been said, I'd still recommend changing the HTML, but if that's not an option for whatever reason, then this should do it.