array_push and in_array problems - php

I am having a bit of difficulty with this. I want to allow a user to check if a username is available through an AJAX request. The AJAX request calls my php and PHP returns true if the username is not available or false if available.
I wanted to merge the username into the array (if found) and then use in_array to locate a match. It isn't working this way however.
$res = // database returns any username that matches - (not an array)
$banned = // database returns an assoc array of banned names
array_push($banned, strtolower($res['user']));
if(!in_array(strtolower($requested), $banned)){
echo 'available';
} else {
echo 'not available';
}
Here is a sample array from the banned variable:
Array
(
[0] => bad1
[1] => bad2
[3] =>
)
The 3rd key is null because it wasn't found in the $res variable.
Is there a better way to do this? I also need to convert the values in the array to lowercase as well.

For readability, I reckon this would look better
if (isset($res['user'])) { // is this key set for this array?
$banned[] = strtolower($res['user']); // append the strtolower`d version
}

Related

Array as variable for in_array

I have a table that I am reading two columns from using PDO::FETCH_KEY_PAIR. I then need check if a value from another query exists in the array returned by the PDO fetch. To illustrate:
$id = array();
/* array returned by PDO::FETCH_KEY_PAIR query */
$mailTo = array (
'MailTo1' => 6143,
'MailTo2' => 6137,
'MailTo3' => 6137,
);
echo $mailTo['MailTo1']; //6143
$result1['needle'] = 'MailTo1'; //needle from second query to seek
if(in_array($result1['needle'], $mailTo)){
$id['mailTo'] = $mailTo[$result1['needle']]; //null
}
using variable $result['needle'] returns null, but to verify that in_array returns the correct element I have used:
if(in_array('MailTo1', $mailTo)){
$id['mailTo'] = $mailTo[$result['needle']]; //6143
}
Hard coding the needle returns the correct element. Taking the needle out an array and passing as a simple variable also returns null, i.e.
$result = 'MailTo1';
if(in_array($result1, $mailTo)){
$id['mailTo'] = $mailTo[$result1]; //null
}
I cannot figure out why passing the needle as a key=>value variable ($result1['needle']) fails. It seems like this is very common practice...
In order to compare keys you need to use array key exists. in_array only looks at values and not the keys.
array_key_exists("MailTo1",$mailTo)
Another approach would be to get all keys in one array and then you can use in_array()
$mailToKeys = array_keys($mailTo);
in_array("MailTo1", $MailToKeys)
DOH!!! Wrong approach.. array_key_exists is what I should have been using!!

Could not search array value

I would like to search value of order using array_search function i have tried following ways but it does not work.
printed array display output
PostDaataArray
(
[order_id] => 5464
)
$currentKey=array_search($orderId,$postedData);
also tried $currentKey=array_search($orderId,array_column($postedData, 'order_id'));
But when i tried to search array using array_search function it does not work also not showing error as well.
If previously data in JSON format then decode it:
$postedData = json_decode($postedData,true);
You can use in_array():
if(in_array($orderId,array_column($postedData, 'order_id'))) //check value is in array
{
$key = array_search($orderId,array_column($postedData, 'order_id')); //return index or key of array
}
else
{
//order id not in array
}
try this:
$PostDaataArray=array("order_id"=>"5464");
foreach($PostDaataArray as $key=>$order_id){
if($order_id=="5464"){
// match found.
}
}

PHP adressing the first key in an array that changes

For example, lets say I have an array that looks liked
$stuff = array('random_string_1' => 'random_value_1','random_string_2' => 'random_value_2');
and then I call the asort() function and it changes the array around. How do I get the new first string without knowing what it actually is?
If you want to get the first value of the array you can use reset
reset($stuff);
If you want to also get the key use key
key($stuff);
If you need to get the first value, do it like this:
$stuff = array('random_string_1' => 'random_value_1','random_string_2' => 'random_value_2');
$values = array_values($stuff); // this is a consequential array with values in the order of the original array
var_dump($values[0]); // get first value..
var_dump($values[1]); // get second value..

Create key => value pair array only if variables are set

I have a number of items of data. Sometimes the var is not created/set, sometimes it is. This is because the var data comes from a form with optional fields.
I have created the variables only if the information is present as such:
if(!empty($_POST["user-jobtitle"])){
$idealJobTitle = $_POST["user-jobtitle"]; }
So if the field user-jobtitle is not filled in, then $idealJobTitle is not created.
I now wish to create an array with a key for each value. But I only want to add to the array if that variable exists. Otherwise, I just want to omit it.
I have written code below which I know is wrong but follows the sort of logic I am after. What is the correct way to do this? Do I really have to run through nested if statements checking if the var exists and only then pushing to the array?
$other_info = array (
"other_info" => array(
if(isset($message)){
"message" => $message
},
if(isset($salaryRange)){
"salary_range" => $salaryRange
},
if(isset($idealJobTitle)){
"ideal_job_title" => $idealJobTitle
}
if(isset($applyFor)){
"ideal_applying_for" => $applyFor
}
)
);
An expected result, if the user has not provided an ideal job title on the form, would be as such:
array(1) {
["other_info"]=>
array(3) {
["message"]=>
string(18) "my message here"
["salary_range"]=>
string(19) "£25k - £30k"
["ideal_applying_for"]=>
string(18) "Cat cuddler"
}
}
As you can see in the above, the ideal_job_title key and value are simply not present.
You should not conditionally declare variables. That's just asking for problems later on.
Unpacking values from one array into a variable and then conditionally packing them back into an array is needlessly complex. Keep your data in an array and move it around in one "package".
You can't have nested if statements within an array declaration.
The most useful way to handle this would be to use names in your form that you're also going to use later on in your $other_info array. Translating between various variable and key names throughout your code is just terribly confusing, pointless and needlessly requires a ton of additional code. In other words, why does the same piece of information need to be called user-jobtitle and $idealJobTitle and ideal_job_title in different contexts? If you'd keep it consistent, you could simply filter empty values and be done with it:
$other_info = array('other_info' => array_filter($_POST));
Yup, array_filter gets rid of empty elements without individual if statements. You can further use array_intersect_key and similar functions to further filter out keys.
If you name variables as key in the array, you can use compact function. Undefined variable will not be in array
$ar = compact("message", "salaryRange", "idealJobTitle", "applyFor");
You can use the below code :
$other_info = array();
if(isset($message)){
$other_info['other_info']["message"] = $message;
}
if(isset($salaryRange)){
$other_info['other_info']["salary_range"] = $salaryRange;
}
if(isset($idealJobTitle)){
$other_info['other_info']["ideal_job_title"] = $idealJobTitle;
}
if(isset($applyFor)){
$other_info['other_info']["ideal_applying_for"] = $applyFor;
}
You already have a code that works and puts the values in variables. Create an empty array and put the data directly in the array under various keys instead of individual variables:
$info = array();
// Analyze the input, put the values in $info at the correct keys
if (! empty($_POST["message"])) {
$info["message"] = $_POST["message"];
};
if (! empty($_POST["salaryRange"])) {
$info["salary_range"] = $_POST["salaryRange"];
};
if (! empty($_POST["idealJobTitle"])) {
$info["ideal_job_title"] = $_POST["idealJobTitle"];
}
if (! empty($_POST["applyFor"])) {
$info["ideal_applying_for"] = $_POST["applyFor"];
}
// Voila! Your data is now in $info instead of several variables
// If you want to get the structure you described in the non-working code you can do:
$other_info = array(
"other_info" => $info,
);

array_search function doesn't check first value

I have an array which gives me correct results when I print it, for example:
[0] => info#mail.com,
[1] => 0909,
[2] => info#mail.com22,
[3] => 0909
Now, when I want to check if info#mail.com is in the array it gives me an error that the value doesnt exist in this array, but when I try for example info#mail.com22 it gives the correct result.
This is a little part of the code:
$user is the word I want to search, $arrayname is the array.
if (array_search(strtolower($user),array_map('strtolower',$arrayname))){
//value exist
}
else{
//value does not exist
}
Now info#mail.com doesn't exist it says, while info#mail.com22 does exist.
Who has any idea?
array_search returns the index of the value that is found. When you search for the first item it returns 0. which is also means false. change your code so that it reads
if (false !== array_search(strtolower($user),array_map('strtolower',$arrayname))){
an alternative method would be to use in_array
if(in_array(strtolower($user),array_map('strtolower',$arrayname))){
I simply use is_numeric
if (is_numeric(array_search(strtolower($user), $arrayname)) {
/* do something */
}

Categories