Can I make a if-else statement based on a array? - php

Here is my current code:
if ( by == 'id') {
handlePromises(identifier_websites)
} else if ( by == 'name'){
handlePromises(names_websites)
} else if ( by == 'email' ) {
handlePromises(email_websites)
} else if ( by == 'phone' ) {
handlePromises(phone_websites)
}
Now I want to make it a little bit more modular (functional). I mean, I want to make the whole code above based on an array like this:
$parts = ['id', 'name', 'email', 'phone'];
So if I add one item to that array, then automatically a else if block should be added to the code based on that item .
Is doing that possible?

Not sure if I get you but here's how you can automate the above slightly.
$parts = [
'id' => identifier_websites,
'name' => names_websites,
'email' => emails_websites,
'phone' => phone_websites
];
foreach ($parts as $cond => $params) {
if (by == $cond) {
handlePromises($params);
break;
}
}

Related

How to I return the first of matching key values?

I have an array that I want to search for a particular value, and then return the key. However, it's likely that there will be multiple matching values. What is the best way to return the key from the first matching value?
$agent_titles = array(
'agent_1' => sales,
'agent_2' => manager, // The key I want to return
'agent_3' => manager,
'agent_4' => director;
);
if (false !== $key = array_search('manager', $agent_titles)) {
return $key;
} else {
return;
}
In this scenario I would want to return 'agent_2'. Thanks in advance!
usage of array_search was best solution
but try write your code simple as possible
$agent_titles=[
'agent_1'=>'sales',
'agent_2'=>'manager',
'agent_3'=>'manager',
'agent_4'=>'director',
];
return array_search('manager',$agent_titles);
public function blahblah($search_value = 'manager') {
$agent_titles = [
'agent_1' => sales,
'agent_2' => manager,
'agent_3' => manager,
'agent_4' => director,
];
foreach($array as $key => $value){
if($value == $search_value){
return $key;
}
}
return false;
}
function getKeyByValue($input, $array) {
foreach ( $array as $key => $value ) {
if ( $input == $value ) {
return $key;
}
}
}
$agent_titles = array(
'agent_1' => 'sales',
'agent_2' => 'manager',
'agent_3' => 'manager',
'agent_4' => 'director'
);
var_dump(getKeyByValue('manager', $agent_titles));

Laravel - Create Array from Dot Notation

I'm not able to do get it right. If I have an array notation like this:
['email', 'privacy.language', 'privacy.phonenr', 'privacy.user.id']
I would like to get an array that looks like this:
[
0 => 'email',
'privacy' => [
0 => 'language',
1 => 'phonenr',
'user' => [
0 => 'id'
]
],
]
My current approach looks like this:
protected function undotArray(array $fields)
{
$array = [];
foreach ($fields as $key => $field) {
$keys = explode('.', $field);
if(count($keys) == 1){
$array[] = $keys[0];
continue;
}
if(count($keys) == 2){
$array[$keys[0]][] = $keys[1];
continue;
}
if(count($keys) == 3){
$array[$keys[0]][$keys[1]][] = $keys[2];
}
}
return $array;
}
But as you see the "if conditions" are similar and they repeat themselves, depending on the number of dots. I feel like that I need to use a recursive function here, but I don't know how.

Comparing two arrays in PHP foreach

What's the best way to compare both two arrays to each other in a foreach loop ?
I have two arrays, which one holds a boolean values and other one represents the real values.
First one of the arrays is some sort of configuration file where I tell what field is a required one TRUE or an optional FALSE:
$rules = array(
'fieldname1' => TRUE,
'fieldname2' => FALSE,
'fieldname3' => TRUE,
'fieldname4' => TRUE,
'fieldname5' => FALSE,
'fieldname6' => FALSE,
'fieldname7' => TRUE,
'fieldname8' => TRUE
);
And the other array which holds incoming data to be worked out:
$fields = array(
'fieldname1' => 'some value',
'fieldname3' => 'some value',
'fieldname4' => 'some value',
'fieldname7' => 'some value',
'fieldname8' => 'some value'
);
How do I make a check in foreach() loop, so the $fields array is going to compare each of its fieldnameX or (keys/indexes) with the other array named $rules ?
For example: $rules['fieldname1'] is required as it have a bool TRUE. So in foreach($fields as $field), the $field named fieldname1 should not be empty, null or false, if so, show an error.
This is a function I did so far which is not doing exactly what I want:
private function check_field_required_exist( $fields )
{
// Read rules from config to work with them accordingly
$rules = config_item('flow.format')[$fields['format']];
// Run throught the rules
foreach( array_keys($rules) as $field )
{
// Check wheter key existance is failed
if( !array_key_exists($field, $fields) )
{
// Checking failed, terminate the process
die('Required field: "'. $field .'" for requested format: "'.$fields['format'].'" does not exists.');
}
}
// Everything is alright
return TRUE;
}
// Goes through all the rules
foreach($rules as $key => $value)
{
// access all fields that are marked as required i.e key set as TRUE
if ($value)
{
//for those whose value is TRUE, check whether the corresponding field is set or
// whether it is empty (NULL,false)
if(!isset($fields[$key]) || empty($fields[$key]))
{
die('Required field does not exist');
}
}
}
foreach ($fields as $field => $value)
{
if (array_key_exists($field, $rules) && $rules[$field] === true)
{
if (!$value || $value == "" || $value === null)
{
die(); // return false;
}
}
}
return true;
I think that you can play around with the array functions in PHP. First thing I would do is to apply array_filter on your rules array. That way, you will only keep the TRUE values (and their indexes, since array_filter keep the index/value association).
Then I would use array_intersect_key to keep only the fields of interest in your fields var. And again array_filter with a custom callback to perform the verification you want to do.
$requiredField = array();
foreach($rules as $key=>$value) {
if($value == true && (!isset($fields[$key]) || $fields[$key] == "" )) {
$requiredField[] = $key;
}
}
if(count($requiredField) > 0) {
echo implode(',',$requiredField)." Are Required";
die;
}
USING PHP Array Functions:
$rules = array('name' => TRUE, 'phoneNumber' => TRUE, 'age' => FALSE);
$submittedFields = array( 'name' => 'aspirinemaga', 'age' => 38, 'phoneNumber' => '');
$requiredFields = array_keys(array_filter($rules));
$validFields = array_keys(array_filter($submittedFields));
$missingFields = array_diff($requiredFields, $validFields);
Given
$rules = array('name' => TRUE, 'phoneNumber' => TRUE, 'age' => FALSE);
$submittedFields = array( 'name' => 'aspirinemaga', 'age' => 38, 'phoneNumber' => '');
PhoneNumber is wrong here.
$requiredFields = array_keys(array_filter($rules));
This gives you the keys of all rule elements that are TRUE.
$validFields = array_keys(array_filter($submittedFields));
Same here, your definition of what's ok is the same as php truth table for boolean conversion. If you have a more advanced check, you could pass a function name into array_filter (see below).
$missingFields = array_diff($requiredFields, $validFields);
This will get you all the fieldNames that exist in $requiredFields but are not in $validFields.
More advanced validation
$rules = array('name' => 'MORE_THAN_3', 'phoneNumber' => TRUE, 'age' => 'POSITIVE');
$submittedFields = array( 'name' => 'aspirinemaga', 'age' => 38, 'phoneNumber' => '');
$requiredFields = array_keys(array_filter($rules));
function validateField($key, $value){
// get the rule (assuming no submittedFields that have no rule)
$rule = $rules[$key];
switch($rule){
case 'MORE_THAN_3': return strlen($value) > 3; break;
case 'POSITIVE': return $value > 0; break;
}
// in case of TRUE/FALSE
return TRUE;
}
$validFields = array_keys(array_filter("validateField", $submittedFields, ARRAY_FILTER_USE_BOTH));
$missingFields = array_diff($requiredFields, $validFields);
If you wanted to do a more advanced validation, you can integrate that nicely into above solution.
Say you wanted name to be more than 3 characters and age to be positive. Write it into your rules:
$rules = array('name' => 'MORE_THAN_3', 'phoneNumber' => TRUE, 'age' => 'POSITIVE');
$submittedFields = array( 'name' => 'aspirinemaga', 'age' => 38, 'phoneNumber' => '');
Required Fields are still the same (to check if one is missing).
$requiredFields = array_keys(array_filter($rules));
Now your validate function would be something like:
function validateField($key, $value){
// get the rule (assuming no submittedFields that have no rule)
$rule = $rules[$key];
switch($rule){
case 'MORE_THAN_3': return strlen($value) > 3; break;
case 'POSITIVE': return $value > 0; break;
}
// in case of TRUE/FALSE
return TRUE;
}
Pass that into array_filter and add to ARRAY_FILTER_USE_BOTH Flag:
$validFields = array_keys(array_filter("validateField", $submittedFields, ARRAY_FILTER_USE_BOTH));
And your missing Fields stays the same.
$missingFields = array_diff($requiredFields, $validFields);
This will only work in PHP 5.6+ (because ARRAY_FILTER_USE_BOTH). Not tested, should work.

Doctrine Repository accept array for getAll

In a repository, I need a custom getALL query which checks for items based on an array of data. e.g. I need to be able to send $params = [ 'type' => [ 'type1', 'type2' ], 'username' => $username ] but I can currently only send one parameter such as: $params = ['type' => 'type1', 'username' => $username].
What would be the best way of adding acceptance of an array (like the one above) to this getAll query?:
public function getAllQuery($params = [])
{
$query = $this->createQueryBuilder('c');
if(count($params))
{
foreach($params as $param => $value)
{
//todo need to make it accept an array of parameters
if(in_array($param, $this->getClassMetadata()->getFieldNames()) && $param != 'deleted')
{
$query
->andWhere(sprintf('c.%1$s LIKE :%1$s', $param))
->setParameter($param, sprintf('%%%s%%', $value));
}
/*code already exists here for checking other parameters
outside of 'type' (e.g. 'username') */
}
}
return $query->getQuery();
}
I am not able to comment so I will answer without to be sur that I've understand the question. Are you waiting something like this ? In this case it's more a PHP problem than Doctrine.
The results of the past code : here.
$params = array( 'type' => array( 'type1', 'type2' ), 'username' => 'flavien');
$requiredFields = array('type');
if(count($params))
{
foreach($params as $param => $value)
{
if(in_array($param, $requiredFields) && $param != 'deleted')
{
if(is_array($value))
{
echo "My param: {$param}" . PHP_EOL;
for($i=0; $i < count($value); $i++) {
echo $value[$i] . PHP_EOL;
}
}
}
}
}

Php Array key=> value searching

HI I am fairly new to php.
I have an array
$arr = array(0 => array('GID'=>1,'groupname'=>"cat1",'members'=>array(0=>array('mid'=>11,'mname'=>'wwww'),1=>array('mid'=>12,'mname'=>'wswww'))),
1 => array('GID'=>2,'groupname'=>"cat2",'members'=>array(0=>array('mid'=>13,'mname'=>'gggwwww'),1=>array('mid'=>14,'mname'=>'wvvwww'))),
2 => array('GID'=>3,'groupname'=>"cat1",'members'=>array(0=>array('mid'=>15,'mname'=>'wwddsww')),1=>array('mid'=>16,'mname'=>'wwwdddw')));
ie...,I have GID,groupname,mid(member id),mname(member name).I want to insert a new mid and mname into a group if it is already in the array ,if it is not exists then create a new subarray with these elements..I also need to check a member id(mid) is also present.........................I used the code but its not working fine............. if (!empty($evntGroup)) {
foreach ($evntGroup as $k => $group) {
if ($group['GID'] == $group_id) {
foreach($group as $j=> $mem){
if($mem['mid'] == $mem_id){
unset($evntGroup[$k]['members'][$j]['mid']);
unset($evntGroup[$k]['members'][$j]['mname']);
}
else{
$evntGroup[$k]['members'][] = array(
'mid' => $mem_id,
'mname' => $mem_name);
}}
} else {
$evntGroup[] = array(
'GID' => $group_id,
'groupname' => $Group['event_group_name'],
'members' => array(
0 => array(
'mid' => $mem_id,
'mname' => $mem_name
)
)
);
}
}
} else {
$evntGroup[$i]['GID'] = $group_id;
$evntGroup[$i]['groupname'] = $Group['event_group_name'];
$evntGroup[$i]['members'][] = array(
'mid' => $mem_id,
'mname' => $mem_name);
$i++;
}
In the form of a function, the easiest solution will look something like this:
function isGidInArray($arr, $val) {
foreach($arr as $cur) {
if($cur['GID'] == $val)
return true;
}
return false;
}
You've updated your question to specify what you want to do if the specified GID is found, but that's just a trivial addition to the loop:
function doSomethingIfGidInArray($arr, $val) {
foreach($arr as $cur) {
if($cur['GID'] == $val) {
doSomething();
break; //Assuming you only expect one instance of the passed value - stop searching after it's found
}
}
}
There is unfortunately no native PHP array function that will retrieve the same index of every array within a parent array. I've often wanted such a thing.
Something like this will match if GID equals 3:
foreach( $arr as $item ) {
if( $item['GID'] == 3 ) {
// matches
}
}
There is the code
function updateByGid(&$array,$gid,$groupname,$mid,$mname) {
//For each element of the array
foreach ($array as $ii => $elem) {
//If GID has the same value
if ($elem['GID'] == $gid) {
//Insert new member
$array[$ii]['members'][]=array(
'mid'=>$mid,
'mname'=>$mname);
//Found!
return 0;
}
}
//If not found, create new
$array[]=array(
'GID'=>$gid,
'groupname'=>$groupname,
'members'=>array(
0=>array(
'mid'=>$mid,
'mname'=>$mname
)
)
);
return 0;
}

Categories