I am trying to find easier and simple way to code a logic.
That is if one variable is equal to any key values in an array.
For instance:
$someArray = array("a","b","c");
If($_GET["foobar"] == $someArray) {
return true;
} else {
return false;
}
If the $_GET["foobar"] had a value of A, B, or C, the case would return true. If it was any other values, it would return false.
Thanks for the help.
return in_array($_GET["foobar"], $someArray, true);
EDIT: Added optional true parameter.
Rather than integer-indexed arrays, you can make use of associative arrays:
$someArray = array('a' => 1, 'b' => 1, 'c' => 1);
if (isset($someArray[$_GET['foobar']])) {
...
}
If you don't like to type out all the array values or the values of $someArray need to stay as they are, you can use array_flip:
$someArray = array('a', 'b', 'c');
...
$otherArray = array_flip($someArray);
if (isset($otherArray[$_GET['foobar']])) {
...
}
You can even store useful information in the values of the associative array.
You can use the in_array() function. I'm pretty sure it's exactly what you are looking for. Here is the function in the code sample you provided.
$someArray = array("a","b","c");
if(in_array($_GET["foobar"],$someArray)) {
return true;
} else {
return false;
}
Related
I have an array like:
$array = array('foo' => 'bar', 33 => 'bin', 'lorem' => 'ipsum');
echo native_function($array, 0); // bar
echo native_function($array, 1); // bin
echo native_function($array, 2); // ipsum
So, this native function would return a value based on a numeric index (second arg), ignoring assoc keys, looking for the real position in array.
Are there any native function to do that in PHP or should I write it?
Thanks
$array = array('foo' => 'bar', 33 => 'bin', 'lorem' => 'ipsum');
$array = array_values($array);
echo $array[0]; //bar
echo $array[1]; //bin
echo $array[2]; //ipsum
array_values() will do pretty much what you want:
$numeric_indexed_array = array_values($your_array);
// $numeric_indexed_array = array('bar', 'bin', 'ipsum');
print($numeric_indexed_array[0]); // bar
I am proposing my idea about it against any disadvantages array_values( ) function, because I think that is not a direct get function.
In this way it have to create a copy of the values numerically indexed array and then access. If PHP does not hide a method that automatically translates an integer in the position of the desired element, maybe a slightly better solution might consist of a function that runs the array with a counter until it leads to the desired position, then return the element reached.
So the work would be optimized for very large array of sizes, since the algorithm would be best performing indices for small, stopping immediately. In the solution highlighted of array_values( ), however, it has to do with a cycle flowing through the whole array, even if, for e.g., I have to access $ array [1].
function array_get_by_index($index, $array) {
$i=0;
foreach ($array as $value) {
if($i==$index) {
return $value;
}
$i++;
}
// may be $index exceedes size of $array. In this case NULL is returned.
return NULL;
}
Yes, for scalar values, a combination of implode and array_slice will do:
$bar = implode(array_slice($array, 0, 1));
$bin = implode(array_slice($array, 1, 1));
$ipsum = implode(array_slice($array, 2, 1));
Or mix it up with array_values and list (thanks #nikic) so that it works with all types of values:
list($bar) = array_values(array_slice($array, 0, 1));
I'm currently using array_map to apply callbacks to elements of an array. But I want to be able to pass an argument to the callback function like array_walk does.
I suppose I could just use array_walk, but I need the return value to be an array like if you use array_map, not TRUE or FALSE.
So is it possible to use array_map and pass an argument to the callback function? Or perhaps make the array_walk return an array instead of boolean?
You don't need it to return an array.
Instead of:
$newArray = array_function_you_are_looking_for($oldArray, $funcName);
It's:
$newArray = $oldArray;
array_walk($newArray, $funcName);
If you want return value is an array, just use array_map. To add additional parameters to array_map use "use", ex:
array_map(function($v) use ($tmp) { return $v * $tmp; }, $array);
or
array_map(function($v) use ($a, $b) { return $a * $b; }, $array);
Depending on what kind of arguments you need to pass, you could create a wrapped function:
$arr = array(2, 4, 6, 8);
function mapper($val, $constant) {
return $val * $constant;
}
$constant = 3;
function wrapper($val) {
return mapper($val, $GLOBALS['constant']);
}
$arr = array_map('wrapper', $arr);
This actually seems too simple to be true. I suspect we'll need more context to really be able to help.
To expand a bit on Hieu's great answer, you can also use the $key => $value pairs of the original array. Here's an example with some code borrowed from comment section http://php.net/manual/en/function.array-map.php
The following will use 'use' and include an additional parameter which is a new array.
Below code will grab "b_value" and "d_value" and put into a new array $new_arr
(useless example to show a point)
// original array
$arr = ("a" => "b_value",
"c" => "d_value");
// new array
$new_arr = array();
array_map(function($k,$v) use (&$new_arr) { $new_arr[] = $v;}, array_keys($arr), $arr);
^ $k is key and $v is value
print_r of $new_arr is
Array
(
[0] => b_value
[1] => d_value
)
Well, I have
$a2 = array('a'=>'Apple','b'=>'bat','c'=>'Cat','d'=>'Dog','e'=>'Eagle','f'=>'Fox','g'=>'God');
$a3 = array('b','e');
I want to substract $a3 from $a2 to get:
$aNew = array('a'=>'Apple','c'=>'Cat','d'=>'Dog','f'=>'Fox','g'=>'God');
Any help?
the are two built-in functions to do something similar: array_diff and array_diff_assoc - but both won't work in your case.
so, to do what you want, you'll have to change the markup of your $a3 a bit to fit these functions (take a look at the documentation), or you'll have to loop $a3 and delete the elements from $a2 manually like this:
foreach($a3 as $k){
unset($a2[$k]);
}
foreach($a3 as $value){
if(isset($a2[$value]))
unset($a2[$value]);
}
Don't get it.
$aNew = $a2;
foreach($a3 as $key) unset($aNew[$key]);
you need this one?
This can be done with php built-in functions.
Since the array $a2 contains the values of the keys you want to remove, you need first to create an array containing the values of $a2 as keys using array_flip. Then you can just use array_diff_key. So try this:
$aNew = array_diff_key($a2, array_flip($a3));
Note that you need php > 5.1.0 for this to work.
$aNew = array();
foreach (array_diff(array_keys($a2), $a3) : $key) {
$aNew[key] = $a2[key];
}
This sould do the job. Grap the keys from a2 remove all keys which exist in a3 and then copy the remaining keys to a new array. You could also remove the keys from the old array. This is up to you.
Edit: +$
The difficulty here lies in that you compare key of one array with values of another one. E.g. by the use of array_diff_ukey.
Excerpt from PHP manual:
function key_compare_func($key1, $key2)
{
if ($key1 == $key2)
return 0;
else if ($key1 > $key2)
return 1;
else
return -1;
}
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);
var_dump(array_diff_ukey($array1, $array2, 'key_compare_func'));
array(2) {
["red"]=>
int(2)
["purple"]=>
int(4)
}
Your second array is not associative, so this would compare "a" with 0, e.g.
So it's:
$compareFunc = function($key) uses ($a3) {
if(array_key_exists($key, $a3) {
return true;
}
else return false;
}
array_map($compareFunc, $a2);
can't be used neither, because this function is used to modify but not to reduce the array.
$a4 = array();
$compareFunc = function($key) uses ($a3, &$a4) {
if(array_key_exists($key, $a3) {
array_push($a4);
}
}
would do the job.
What I am trying to achieve is:
Play around with the PHP - functions that provide callbacks to you when the standart - functions don't succeed.
Try using the concept of binding, when the describtion of the callback doesn't fit your needs. With PHP's Lambda - functions you can bind objects / variables to a function,
so that you have access to variables that are not passed to the callback.
Get creative!!!
Try using array_diff
but you need to make some changes on your $a3.
$a3 = array('bat', 'Eagle');
//and then
$a4 = array_diff($a2, $3);
because without specifying a key (in key => value format), the string will automatically become a value instead.
I need to remove from an array some keys.
$array = array('a' => 'a', 'b' => 'b', 'c' => 'c');
unset($array['a']);
unset($array['b']);
How can I do this more elegance? Maybe there is a function like this array_keys_unset('a', 'b')?I don't need array_values or foreach. I only want to know is it possible.
Thank you in advance. Sorry for my english and childlike question.
You can do that with single call to unset as:
unset($array['a'],$array['b']);
unset() is as simple as it gets, but as another solution how about this?
$keys_to_remove = array_flip(array('a', 'b'));
$array = array_diff_key($array, $keys_to_remove);
Put into a function:
function array_unset_keys(array $input, $keys) {
if (!is_array($keys))
$keys = array($keys => 0);
else
$keys = array_flip($keys);
return array_diff_key($input, $keys);
}
$array = array_unset_keys($array, array('a', 'b'));
Or you could even make it unset()-like by passing it a variable number of arguments, like this:
function array_unset_keys(array $input) {
if (func_num_args() == 1)
return $input;
$keys = array_flip(array_slice(func_get_args(), 1));
return array_diff_key($input, $keys);
}
$array = array_unset_keys($array, 'a', 'b');
Personally, I would just do this if I had a long / arbitrary list of keys to set:
foreach (array('a', 'b') as $key) unset($array[$key]);
You could use a combination of array functions like array_diff_key(), but I think the above is the easiest to remember.
What's wrong with unset()?
Note that you can do unset($array['a'], $array['b']);
You could also write a function like the one you suggested, but I'd use an array instead of variable parameters.
No, there is no predefined function like array_keys_unset.
You could either pass unset multiple variables:
unset($array['a'], $array['b']);
Or you write such a array_keys_unset yourself:
function array_keys_unset(array &$arr) {
foreach (array_slice(func_get_args(), 1) as $key) {
unset($arr[$key]);
}
}
The call of that function would then be similar to yours:
array_keys_unset($array, 'a', 'b');
I need to get the keys from values that are duplicates. I tried to use array_search and that worked fine, BUT I only got the first value as a hit.
I need to get both keys from the duplicate values, in this case 0 and 2. The search result output as an array would be good.
Is there a PHP function to do this or do I need to write some multiple loops to do it?
$list[0][0] = "2009-09-09";
$list[0][1] = "2009-05-05";
$list[0][2] = "2009-09-09";
$list[1][0] = "first-paid";
$list[1][1] = "1";
$list[1][2] = "last-unpaid";
echo array_search("2009-09-09",$list[0]);
You want array_keys with the search value
array_keys($list[0], "2009-09-09");
which will return an array of the keys with the specified value, in your case [0, 2]. If you want to find the duplicates as well, you can first make a pass with array_unique, then iterate over that array using array_keys on the original; anything which returns an array of length > 1 is a duplicate, and the result is the keys in which the duplicates are stored. Something like...
$uniqueKeys = array_unique($list[0])
foreach ($uniqueKeys as $uniqueKey)
{
$v = array_keys($list[0], $uniqueKey);
if (count($v) > 1)
{
foreach ($v as $key)
{
// Work with $list[0][$key]
}
}
}
In array_search() we can read:
If needle is found in haystack more
than once, the first matching key is
returned. To return the keys for all
matching values, use array_keys() with
the optional search_value parameter
instead.
The following combination of function calls will give you all duplicate values:
$a = array(1, 1, 2, 3, 4, 5, 99, 2, 5, 2);
$unique = array_unique($a); // preserves keys
$diffkeys = array_diff_key($a, $unique);
$duplicates = array_unique($diffkeys);
echo 'Duplicates: ' . join(' ', $duplicates) . "\n"; // 1 2 5
You can achieve that using array_search() by using while loop and the following workaround:
while (($key = array_search("2009-09-09", $list[0])) !== FALSE) {
print($key);
unset($list[0][$key]);
}
Source: cue at openxbox at php.net
For one-multidimensional array, you may use the following function to achieve that (as alternative to array_keys()):
function array_isearch($str, $array){
$found = array();
foreach ($array as $k => $v) {
if (strtolower($v) == strtolower($str)) {
$found[] = $k;
}
}
return $found;
}
Source: robertark, php.net
The PHP manual states in the Return Value section of the array_search() function documentation that you can use array_keys() to accomplish this. You just need to provide the second parameter:
$keys = array_keys($list[0], "2009-09-09");
$userdb=Array
(
(0) => Array
(
(uid) => '100',
(name) => 'Sandra Shush',
(url) => 'urlof100'
),
);
$key = array_search(100, array_column($userdb, 'uid'));