How to compare textbox value if exist in 2d array? - php

I have this code and I need to compare the user input and the hardcoded 2d array. Can somebody help me with this? Thanks!
if (isset($_POST['submit']))
{
$array = array
(
0=>array
( 'username'=>'Art',
'password'=>'p#ssw0rd',
'user_id'=>'1'
),
1=>array
( 'username'=>'Berto',
'password'=>'1234',
'user_id'=>'2'
),
2=>array
( 'username'=>'Carrie',
'password'=>'5678',
'user_id'=>'3'
),
3=>array
( 'username'=>'Dino',
'password'=>'qwer',
'user_id'=>'4'
),
4=>array
( 'username'=>'Ely',
'password'=>'asdf',
'user_id'=>'5'
)
);
if(in_array($_POST['user'], $users))
{
$key = array_search($_POST['user'], $users);
I want to match the username if it exist through the 2d array. It is also the same for the password field.

You can do this through foreach loop
foreach($array as $key=>$value)
{
if($value['username'] == $_POST['user'] && $value['password'] == $_POST['pwd'])
{
// do whatever you want to do here
}
}

function searchForValue($fkey, $uvalue, $array) {
foreach ($array as $key => $val) {
if ($val[$fkey] == $uvalue) {
return $key;
}
}
return null;
}
call it like this
$id = searchForValue('username', $_POST['user'], $<yourarray>);
in case of password search
$id = searchForValue('password', $_POST['pass'], $<yourarray>);

You've defined your array name as $array but using $users in the in_array().
Anyways, suppose you use the correct name, you can match like this:
foreach ($users as $key => $item)
{
if ($item['username'] === $_POST['user'] &&
$item['password'] === $_POST['password'])
return $key;
return false;
}

Related

Find ARRAY by to its values

I have a multi-dimensional array like so:
$a = array(
'potatoe'=> array(
'weight'=>24,
'label'=>'kon',
'year'=>2001,
),
'apple'=> array(
'weight'=>55,
'label'=>'krakat',
'year'=>1992,
)
);
I am looking for a way to searching the fruit name (with its values) when I only know weight is 55 and year is 1992. How to do that?
Something like this perhaps
foreach ($a as $key => $value) {
if ($value['weight'] == 55 && $value['year'] == 1992) {
echo $key;
}
}
Outputs
apple
You will have to iterate over it using foreach and test every element.
function findFruit($array,$weight, $year){
foreach($array as $key => $fruit){
if($fruit['weight'] == $weight && $fruit['year'] == $year ){
return $key;
}
}
}
then, just use the function:
$theFruit = $a[findFruit($a,55,1992)];

PHP - Find Specific Value in Array (multidimensional)

I have the an array, in which I store one value from the database like this:
$stmt = $dbh->prepare("SELECT token FROM advertisement_clicks WHERE (username=:username OR ip=:ipcheck)");
$stmt->bindParam(":username",$userdata["username"]);
$stmt->bindParam(":ipcheck",$ipcheck);
$stmt->execute();
$data = array();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
So, that gives me: array("token","token");
When I print it:
Array ( [0] => Array ( [token] => 677E2114AA26BA4351A686917652C7E1BA67A32D ) [1] => Array ( [token] => C42190F3D72C5BB6BB6B68488D1D4662A8D2A138 ) )
I then have a loop, that loops all the tokens. In that loop, I try to search for a specific token, and if it that token matches, it will be marked as "seen":
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['token'] === $id) {
return $key;
}
}
}
This is my loop:
$icon = "not-seen";
foreach($d as $value){
$token = $value["token"];
$searchParam = searchForId($token, $data);
if($searchParam == $token){
$icon = "seen";
}
}
However, searchForid() simply returns 0
What am I doing wrong?
Ok, here you can see a PHP fiddle that works
$data = array();
$data[] = array('token'=>'123');
$data[] = array('token'=>'456');
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['token'] === $id) {
return true;
}
}
return false;
}
$icon = "not-seen";
foreach($data as $value){
$token = $value["token"];
$searchParam = searchForId($token, $data);
if($searchParam){
$icon = "seen";
}
}
echo $icon;
It echos 'seen' which is expected since I compare the same array values, now assuming that your $d variable has different tokens, it should still work this way.
That means that your $d array does not contain what you claim it contains, could you print_r this variable and post it in your answer?

Weird is_array() behaviour in PHP

I have form with several fields I want to store those values in a session variable. Some of those fields should be 0 if the user doesn't fill them in.
A print_r($_POST) after submitting the form shows:
[report] => Array
(
[a_name] => Array
(
[0] =>
)
[a_id_card] => Array
(
[0] =>
)
[a_total] =>
Yet, after running the following PHP code, it seems that "a_name" and "a_id_card" are not interpreted as arrays. Any ideea why?
if (isset($_POST['submit'])) {
foreach ($_POST as $key => $value) {
if (!is_array($key) && trim($value) == '') {
$value = 0;
$_SESSION['report'][$key] = $value;
} else {
$_SESSION['report'][$key] = $value;
}
}
}
think you want to write this - is_array($value)
$key is the string 'report'. So is_array($key) == false. However $_POST[$key] or $value is an array.
The key is never an array. It is always a scalar or string. The value, on the other hand, can be an array.
Maybe you want look only $_POST['report'], and check if 'value' is or not an array (not key):
if (isset($_POST['submit'])) {
foreach ($_POST['report'] as $key => $value) {
if (!is_array($value) && trim($value) == '') {
$value = 0;
$_SESSION['report'][$key] = $value;
} else {
$_SESSION['report'][$key] = $value;
}
}
}

Get keys from multidimensional array according to other keys

I have a multidimensional array like this which I converted from JSON:
Array (
[1] => Array (
[name] => Test
[id] => [1]
)
[2] => Array (
[name] => Hello
[id] => [2]
)
)
How can I return the value of id if name is equal to the one the user provided? (e.g if the user typed "Test", I want it to return "1")
Edit: Here's the code that works if anyone wants it:
$array = json_decode(file_get_contents("json.json"), true);
foreach($array as $item) {
if($item["name"] == "Test")
echo $item["id"];
}
The classical solution is to simply iterate over the array with foreach and check the name of each row. When it matches your search term you have found the id you are looking for, so break to stop searching and do something with that value.
If you are using PHP 5.5, a convenient solution that works well with less-than-huge data sets would be to use array_column:
$indexed = array_column($data, 'id', 'name');
echo $indexed['Test']; // 1
You can use this function
function searchObject($value,$index,$array) {
foreach ($array as $key => $val) {
if ($val[$index] === $value)
return $val;
}
return null;
}
$MyObject= searchObject("Hello","name",$MyArray);
$id = $MyObject["id"];
You can do it manually like, in some function:
function find($items, $something){
foreach($items as $item)
{
if ($item["name"] === $something)
return $item["id"];
}
return false;
}
here is the solution
$count = count($array);
$name = $_POST['name']; //the name which user provided
for($i=1;$i<=$count;$i++)
{
if($array[$i]['name']==$name)
{
echo $i;
break;
}
}
enjoy
Try this:
$name = "Test";
foreach($your_array as $arr){
if($arr['name'] == $name){
echo $arr['id'];
}
}

Check if values in mysql database exist in multi dimensional array

I have multiple ID's in an mysql database. I would like to know if there are ID's in the database which are not present in an multi dimensional array. For each ID which is not present in the multi dimensional array the row needs te be deleted. The following code is what I have so far.
function multi_array_search($search_for, $search_in) {
foreach ($search_in as $element) {
if ( ($element === $search_for) ) {
return true;
} elseif (is_array($element)) {
$result = multi_array_search($search_for, $element);
if($result == true)
return true;
}
}
return false;
}
$output = mysql_query("SELECT id FROM ads");
while ($g = mysql_fetch_array($output)) {
echo multi_array_search("$g", $arr) ? 'Found' : 'Not found';
}
I don't think the above code is correct for what I want?
Information:
The $arr looks like:
Array (
[0] => Array (
[url] => http://
[id] => 752
)
[1] => Array (
[url] => http://
[id] => 758
)
)
I tryed some solutions now and none of the mare working :(
Every thing seems to be fine. Just few updates to remove unwanted code from elseif and add one more check !empty into elseif condition.
function multi_array_search($search_for, $search_in) {
foreach ($search_in as $element) {
if ($element === $search_for){
return true;
}elseif(is_array($element) && !empty($element)){
$result = multi_array_search($search_for, $element);
}
}
return false;
}
$output = mysql_query("SELECT id FROM ads");
while ($g = mysql_fetch_array($output)) {
echo multi_array_search("$g", $arr) ? 'Found' : 'Not found';
}
Hope will help!
$removeid=array();
$idarray is the multi dimensional array you want to check your database id with.
$result = 'store your databse id here in the form of an array';
foreach ($result as $key => $value) {
$result=$value;
if(!empty($result))
{
foreach ($idarray as $key => $value) {
if ($value["id"] != $result) {
$removeid=$key;
}
}
}
}
now $removeid contains the id to be removed from the databse
$un_array = array();
foreach ($array as $h) {
$id = $h['id'];
array_push($un_array, $id);
}
$db_array = array();
$output = mysql_query("SELECT id FROM account WHERE account='$username'");
while ($g = mysql_fetch_assoc($output)) {
$id = $g['id'];
array_push($db_array, $id);
}
$result = array_diff($db_array, $un_array);
foreach ($result as $r) {
mysql_query("DELETE FROM account WHERE id='$r'");
}

Categories