Array as variable for in_array - php

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!!

Related

array_dif not working as the output is empty

I created 2 arrays and want to check for the difference between both arrays (values). If I use my arrays with the function array_diff, the response is a empty Array, which is very wierd as I can't find the problem at all.
My setup:
// first array
$listing_products_sku = [
'55995', '55996', '55999', '56000', '56005', '56006', '56007',
'56008', '56021', '56022', '56023', '56024', '56029', '56030',
'56031', '56032', '56036', '56037',
];
// second array:
$internal_products_sku = [
'56015', '56016', '56014', '56018', '56019', '56020', '55994',
'55995', '55996', '55997', '55998', '55999', '56000', '56001',
'56002', '56003', '56005', '56004', '56006', '56007', '56008',
'56009', '56010', '56011', '56012', '56013', '56017', '56021',
'56022', '56023', '56024', '56025', '56026', '56027', '56028',
'56029', '56030', '56031', '56032', '56033', '56034', '56035',
'56036', '56037', '56038', '56039', '56040', '56041', '60434',
'60435',
];
// used function:
$diff_result = array_diff($listing_products_sku, $internal_products_sku);
print_r($diff_result);
Output
Array ( )
Help needed
Is anybody able to explain why this happens and how I can make this working?
array_diff() returns array from first array containing values not exist in rest of the arrays (http://php.net/manual/en/function.array-diff.php). As your first array's element are already exist in second array ($internal_products_sku) this is why its returning empty array.
So to find the difference all you have to do is take the $internal_products_sku array as first param then check
$diff_result = array_diff($internal_products_sku, $listing_products_sku);
print_r($diff_result);
Now it will return an array with those value not exist in $listing_products_sku

Using empty string as key in associative array

I need to select and group some items according to some values and it's easy using an associative multidimensional array:
$Groups = array(
"Value1" = array("Item1", "Item3"),
"Value2" = array("Item2", "Item4")
);
But some items hasn't the value so my array will be something like:
$Groups = array(
"Value1" = array("Item1", "Item3"),
"Value2" = array("Item2", "Item4")
"" = array("Item5", "Item6")
);
I've tested it (also in a foreach loop) and all seems to work fine but I'm pretty new to php and I'm worried that using an empty key could give me unexpected issues.
Is there any problem in using associative array with empty key?
Is it a bad practice?
If so, how could I reach my goal?
There's no such thing as an empty key. The key can be an empty string, but you can still access it always at $groups[""].
The useful thing of associative arrays is the association, so whether it makes sense to have an empty string as an array key is up to how you associate that key to the value.
You can use an empty string as a key, but be careful, cause null value will be converted to empty string:
<?php
$a = ['' => 1];
echo $a[''];
// prints 1
echo $a[null];
// also prints 1
I think, it's better to declare some "no value" constant (which actually has a value) and use it as an array key:
<?php
define('NO_VALUE_KEY', 'the_key_without_value');
$a = [NO_VALUE_KEY => 1];

PHP JSON Arrays within an Array

I have a script that loops through and retrieves some specified values and adds them to a php array. I then have it return the value to this script:
//Returns the php array to loop through
$test_list= $db->DatabaseRequest($testing);
//Loops through the $test_list array and retrieves a row for each value
foreach ($test_list as $id => $test) {
$getList = $db->getTest($test['id']);
$id_export[] = $getList ;
}
print(json_encode($id_export));
This returns a JSON value of:
[[{"id":1,"amount":2,"type":"0"}], [{"id":2,"amount":25,"type":"0"}]]
This is causing problems when I try to parse the data onto my android App. The result needs to be something like this:
[{"id":1,"amount":2,"type":"0"}, {"id":2,"amount":25,"type":"0"}]
I realize that the loop is adding the array into another array. My question is how can I loop through a php array and put or keep all of those values into an array and output them in the JSON format above?
of course I think $getList contains an array you database's columns,
use
$id_export[] = $getList[0]
Maybe can do some checks to verify if your $getList array is effectively 1 size
$db->getTest() seems to be returning an array of a single object, maybe more, which you are then adding to a new array. Try one of the following:
If there will only ever be one row, just get the 0 index (the simplest):
$id_export[] = $db->getTest($test['id'])[0];
Or get the current array item:
$getList = $db->getTest($test['id']);
$id_export[] = current($getList); //optionally reset()
If there may be more than one row, merge them (probably a better and safer idea regardless):
$getList = $db->getTest($test['id']);
$id_export = array_merge((array)$id_export, $getList);

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..

PHP array_search trouble

$data = Array
(
[68315163] => Donnie1
[68328887] => Donnie1
[68353339] => Donnie1
)
I want to get the all the keys for Donnie1 value it is showing only the first one
$datum = array_search('Donnie1', $data);
print_r($datum);
Where am I going wrong?
array_search() does not search array keys. It only searches array values.
Getting this value is basic PHP:
$datum = $data['68315163'];
array_search('68315163', $data) doesn't return anything useful because the value you're searching for is not in the array.
This function searches through the values, and returns the key at the found value. Please see the docs.
Array
(
[68315163] => Donnie
[68328887] => Donnie1
[68353339] => Donnie2
)
$datum = array_search('Donnie1', $data);
echo $datum;// return only value of given key: 68328887
You are passing wrong parameters to array_search(). you need to pass value of array then this function will return matching key;
array_search() does not return array. It only returns the first key.
array_keys() would be the correct function for this use. It returns an array of all keys with the given value.
$datum = array_keys($data, "Donnie1");

Categories