PHP - in_array isn't finding my value [duplicate] - php

This question already has answers here:
in_array() and multidimensional array
(24 answers)
Closed 8 years ago.
I'm a newb and I got a problem with in_array...
So this is my array $allUsers (received by a SQL-Query for Usernames)
Array
(
[0] => Array
(
[name] => test
)
[1] => Array
(
[name] => test2
)
[2] => Array
(
[name] => admin
)
[3] => Array
(
[name] => kingChräbi
)
Now If a new member wants to register, I want to check in this array if it's already existent:
if(!in_array($username,$allUsers)){....
eventhough it is to when $username is NOT in $allUsers do .... it's just skipping to else also if the user is existing :(
$username is set before with
$username = $_POST['name'];
and working as it should (i can echo it without a problem, is exactly test or test2 without whitespace or anything)
I really looked around alot, but I can't find anything like my problem here... Could you please help me?
Thanks

although question itself is quite silly, as you have to realize what array you are working with, the quick solution, based on PDO tag, would be as follows: instead of fetchAll() use fetchAll(PDO::FETCH_COLUMN)
Or, rather you need to learn SQL as well, and find users not by means of selecting them ALL from database which makes no sense, but by asking a database to find a user for you
$stm = $pdo->prepare("SELECT * FROM table WHERE name=?");
$stm->execute(array($_POST['name']));
$user = $stm->fetch();
if ($user) { // <---HERE YOU GO

The in_array() does not work with multi-dimensional arrays. You better flatten your array and then do a search for the keyword.
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr)); //<-- Pass your array here
$new_arr = array();
foreach($it as $v) {
$new_arr[]=$v;
}
if(in_array('test',$new_arr))
{
echo "Exists !";
}
Working Demo

You are searching a 2-D array for a value under the key of "name".
Using array_map() or simple foreach loop should work -
$username = "admin";
$key = "name";
if(!in_array($username,array_map(function($v)use($key){return $v[$key];},$allUsers))){
echo "No found";
}else{
echo "Found";
}

If you are using:
While ($ row=mysql_fetch_assoc ($ result) {
$ data [] = $ row
}
Remove the [] to not create a multidimensional array.

Related

Assignation does't take effect inside two-dimension array [duplicate]

This question already has answers here:
PHP foreach change original array values [duplicate]
(5 answers)
Closed 3 years ago.
I have an array full of credentials following this pattern:
Array (
[0] : Array (
"login" => "toto"
"passwd" => "mdpsecrethashe"
)
[1] : Array (
"login" => "titi"
"passwd" => "supermdp"
)
[2] : Array (
[...]
)
[...]
)
I want to get the desired credentials thanks to the login and change the password. Here is my attempt:
function getListWithModifiedPassword($credentials_list, $wanted_login, $new_password){
echo(print_r($credentials_list, TRUE));
foreach ($credentials_list as $credentials)
if ($credentials['login'] === $wanted_login)
$credentials['passwd'] = hash('whirlpool', $new_password);
echo(print_r($credentials_list, TRUE));
return $credentials_list;
}
Assignation on line 5 doesn't want to work whatever the value (no change between the two echo(print_r($credentials_list, TRUE));, even though the condition on line 4 is true (tested: if I replace line 5 with echo "Hello world\n"; it works).
What is happenning in here ?
In PHP's foreach loop you are working with copy of the array. So your assignation to $credentials['passwd'] does not take effect for $credentials_list.
You have 2 options:
pass to the foreach reference value (notice & before $credentials in foreach bracket and also unset function which stops accidental assignation to the variable after foreach - see docs):
foreach($credentials_list as &$credentials) {
if ($credentials['login'] === $wanted_login)
$credentials['passwd'] = hash('whirlpool', $new_password);
}
unset($credentials);
assign value directly into original array:
foreach($credentials_list as $key => $credentials) {
if ($credentials['login'] === $wanted_login)
$credentials_list[$key]['passwd'] = hash('whirlpool', $new_password);
}
Have a good day! :)
instead write this to print
var_dump($credentials_list);
if you are returning the value then no need to print_r or echo

php find sentence with most match in sql database

I am making a question answering app and as a part of it, it needs to look at your previous questions which are stored in a SQL database and find the previous questions that has the most matching words and then it will take an attribute from the DB for that line.
I have been able to get it to produce an array of matching words for each row in the database. But I need a way of organizing those arrays to select the one with the most matches. here is the SQL and the PHP I have used to far.
$questions1 = $_GET['question'];
$questionsarray = explode(" ",$questions1);
The new question was turned into an array, below it will be compared against all other questions for match's
$sql = "SELECT * FROM records WHERE userid= '24.9.71.79'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$questionsasked = $row['old_questions'];
// turns old question into an array
$last_q_array = explode(" ",$questionsasked);
//finds matches between the old and new question
$intersectarray = array_intersect($last_q_array,$questionsarray);
It then uses array_diff() to clean out common words to help it focus on finding the true topic
$cleanedarray = array_diff($intersectarray ,$commonwords);
//prints the array if it find matches and sets the var
if(count($cleanedarray)>0) {
print_r($cleanedarray);
$desiredattri = $row[last_answer_type];
echo "<br />----------------<br />";
}
}
}
I'm using print_r just for testing. So it does a great job of producing a handful of arrays that show just the matching words. that looks something like this
Array ( [3] => card )
----------------
Array ( [3] => card [7] => work? )
----------------
Array ( [0] => find [2] => card [7] => work? )
So now I need to find a way to parse those arrays and find the one that has the most matches. I can use count() to count the matches in each array but still need to compare that number against the rest of the array counts and then use the attribute of the array with most matches.
You could try something like this. It will use the words themselves as array keys and the array value is the count.
$result = array();
foreach ($cleanedarray as $word) {
if (!array_key_exists($word, $result)) {
$result[$word] = 0;
}
$result[$word]++; // keep count using the word as key
}
I'm sure there might be other built-in PHP functions which could do this for you, but this was a quick-n-dirty way that came to me off hand.

Print specific array key

I need to use a key from an array for a check.
The array comes from a PDO query like this
function getProject($proj_id) {
$database = new Database();
$database->query( "SELECT * FROM projects WHERE proj_id = '$proj_id' LIMIT 1" );
$project = $database->resultSet();
return $project;
}
Then I print the array which works like it should.
$project = getProject(1);
print_r($project);
Array ( [0] => Array ( [proj_id] => 73 [proj_name] => Cake )
But when I try to print a specific key from the array like this:
print_r($project['proj_name'];
Nothing gets printed on the screen. Why not?
You have two arrays:
Array ( [0] => Array ( [proj_id] => 73 [proj_name] => Cake )
^--this one ^--and this one
You need to do:
print_r($project[0]['proj_name']);
Probably the ideal situation would actually be to change it here:
function getProject($proj_id) {
$database = new Database();
$database->query( "SELECT * FROM projects WHERE proj_id = '$proj_id' LIMIT 1" );
$project = $database->resultSet();
return $project[0]; //<---added the [0] this line
}
since you know it will always return one
If you look carefully, you'll see that you have two arrays nested one inside the other. Try print_r($project[0]['proj_name'];
You're missing a close-paren ) at the end of your print_r call.
You're seeing nothing on the screen because this means the file cannot be parsed, and errors are being logged to a file rather than displayed on screen. See How do I get PHP errors to display? for how to fix that.

How to detect duplicate php Array

I have this array:-
Array ( [0] => Prefectorial Board/Prefect/2011 [1] => Prefectorial Board/Head Prefect/2011 [2] => Class Positions/Head Prefect/2011 [3] => Prefectorial Board/Head Prefect/2011 )
How to detect this array have duplicate value and I want the participant to re-fill in his data.
I have try to use this method to detect:-
$max = max(array_values($lr_str));
$keys = array_keys($lr_str, $max);
but it seem like not work for me.
any idea on this?
thanks for advance.
I do not know if I understand you correctly, but you can test the array has duplicated values by using this:
if (count($your_array) === count(array_unique($your_array)) {
// array has no duplicated values
} else {
// array has duplicated values - see compared arrays
}
Are you looking for array_unique?
You can use array_unique() to remove duplicate values. If no values were removed then the returned array should have the same number of items as the original:
if(count($lr_str) == count(array_unique($lr_str))){
//tell participant to re=fill their data
}

How to search array for duplicates using a single array?

I am checking a list of 10 spots, each spot w/ 3 top users to see if a user is in an array before echoing and storing.
foreach($top_10['top_10'] as $top10) //loop each spot
{
$getuser = ltrim($top10['url'], " users/" ); //strip url
if ($usercount < 3) {
if ((array_search($getuser, $array) !== true)) {
echo $getuser;
$array[$c++] = $getuser;
}
else {
echo "duplicate <br /><br />";
}
}
}
The problem I am having is that for every loop, it creates a multi-dimensional array for some reason which only allows array_search to search the current array and not all combined. I am wanting to store everything in the same $array. This is what I see after a print_r($array)
Array ( [0] => 120728 [1] => 205247 ) Array ( [0] => 232123 [1] => 091928 )
There seems to be more to this code. As there are variables being called in it that aren't defined, such as $c, $usercount, etc.. And using array_search with the 2nd parameter of $array if it doesn't exist is not a good idea also. Since it seems like $array is being set within the if statement for this only.
And you don't seem to be using the $top10 value within the foreach loop at all..., why is this?
It would help to see more of the code for me to be able to help you.

Categories