In_array but with more values - php

Example:
$array = array('hi', 'hello', 'bye');
How can I check if at least one of two or more values are present in the array ?
like:
if(in_array('hi', $array) || in_array('hello', $array)) ...
but with a single check? can it be done?

if(count(array_intersect(array('hi','hello','bye'), $array))) {
...
}

function in_array2($ary1,$ary2){
return count(array_intersect($ary1,$ary2)) > 0;
}
Simple, make use of array_intersect.

Take a look at preg_grep, which will return entries in an array that match a predefined pattern (e.g. '/^(hi|hello)$/ in your example).
E.g.
if (count(preg_grep('^/(hi|hello)$/',$array)))
{
// your code
}

use array_intersect()... i.e.
$array = array('hi', 'hello', 'bye');
if(count(array_intersect($array, array('search', 'for', 'values')))>0) ....

Related

Finding position of data in the array - PHP

I have a PHP array, say,
$array = Array("Name1","Name2","Name3","Name4","Name5");
I want to find the position of these names in the array.
I want to return 0 for Name1 and 2 for Name3.
How can I do this?
Do you mean:
$key = array_search('Name1', $array);
Ref: array_search
$pos = array_search("Name3", $array);
Should be what you are looking for, note that to be safe, result checking should be using === (three equal signs) so that those returning 0 (if you are looking for thing in the first element) is also checked for type when you are comparing them in an if statement
if(array_search($name, $array) === 0)
Something like that:
<?php
$array = Array("Name1", "Name2", "Name3", "Name4", "Name5");
$searchValue = "Name1";
$keys = array_keys($array, $searchValue);
// test it
print_r($keys);
?>

How to parse key/value chain into associative array in PHP?

I have a string that looks like: key1/value1/key2/value2/ and so on
I did an explode('/',trim($mystring,'/')) on that
Now I want to haven an associative array like:
array(
'key1' => 'value1',
'key2' => 'value2',
...
);
of course i can do it with an for loop where i always read two entries and push them into a target array, but isnt there something more efficient and elegant? a one liner with some some php core function similar to ·list()· or something?
A method using array_walk() with a callback function:
function buildNewArray($value, $key, &$newArray) {
(($key % 2) == 0) ? $newArray[$value] = '' : $newArray[end(array_keys($newArray))] = $value;
}
$myString = 'key1/value1/key2/value2/';
$myArray = explode('/',trim($myString,'/'));
$newArray = array();
array_walk($myArray, 'buildNewArray', &$newArray);
var_dump($newArray);
If the format is not changin (i mean it is allways Key1/value1/key2/value2) it should be easy.
After the explode you have this:
$arr = Array('key1','value1','key2','value2')
so you now can do:
$new_arr = array();
$i = 0;
for($i=0;$i<count($arr);$i+=2)
{
$new_arr[$arr[i]] = $arr[$i+1];
}
at the end of the loop you will have:
$new_arr = array("key1"=>"value1","key2"=>"value2")
KISS :)
HTH!
One can always make yourself a one liner.
This is called User-defined functions
No need to devise something ugly-but-one-liner-at-any-cost.
Make your own function and you will get much shorter, cleaner and way more reliable result.
A function, which will not only do elementary string operations but also do something more intelligent, like parameter validation.

how to search an array in php?

suppose I have an array of names, what I want is that I want to search this particular array against the string or regular expression and then store the found matches in another array. Is this possible ? if yes then please can your give me hint ? I am new to programming.
To offer yet another solution, I would recommend using PHP's internal array_filter to perform the search.
function applyFilter($element){
// test the element and see if it's a match to
// what you're looking for
}
$matches = array_filter($myArray,'applyFilter');
As of PHP 5.3, you can use an anonymous function (same code as above, just declared differently):
$matches = array_filter($myArray, function($element) {
// test the element and see if it's a match to
// what you're looking for
});
what you would need to di is map the array with a callback like so:
array_filter($myarray,"CheckMatches");
function CheckMatches($key,$val)
{
if(preg_match("...",$val,$match))
{
return $match[2];
}
}
This will run the callback for every element in the array!
Updated to array_filter
well in this case you would probably do something along the lines of a foreach loop to iterate through the array to find what you are looking for.
foreach ($array as $value) {
if ($searching_for === $value) {/* You've found what you were looking for, good job! */}
}
If you wish to use a PHP built in method, you can use in_array
$array = array("1", "2", "3");
if (in_array("2", $array)) echo 'Found ya!';
1) Store the strings in array1
2) array2 against you want to match
3) array3 in which you store the matches
$array1 = array("1","6","3");
$array2 = array("1","2","3","4","5","6","7");
foreach($array1 as $key=>$value){
if(in_array($value,$array2))
$array3[] = $value;
}
echo '<pre>';
print_r($array3);
echo '</pre>';

php elegance keys unsetting

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');

Search an array for a matching string

I am looking for away to check if a string exists as an array value in an array is that possible and how would I do it with PHP?
If you simply want to know if it exists, use in_array(), e.g.:
$exists = in_array("needle", $haystack);
If you want to know its corresponding key, use array_search(), e.g.:
$key = array_search("needle", $haystack);
// will return key for found value, or FALSE if not found
You can use PHP's in_array function to see if it exists, or array_search to see where it is.
Example:
$a = array('a'=>'dog', 'b'=>'fish');
in_array('dog', $a); //true
in_array('cat', $a); //false
array_search('dog', $a); //'a'
array_search('cat', $a); //false
Php inArray()
Incidentally, although you probably should use either in_array or array_search like these fine gentlemen suggest, just so you know how to do a manual search in case you ever need to do one, you can also do this:
<?php
// $arr is the array to be searched, $needle the string to find.
// $found is true if the string is found, false otherwise.
$found = false;
foreach($arr as $key => $value) {
if($value == $needle) {
$found = true;
break;
}
}
?>
I know it seems silly to do a manual search to find a string - and it is - but you may one day wish to do more complicated things with arrays, so it's good to know how to actually get at each $key-$value pair.
Here you go:
http://www.php.net/manual/en/function.array-search.php
The array_search function does exactly what you want.
$index = array_search("string to search for", $array);
Say we have this array:
<?php
$array = array(
1 => 'foo',
2 => 'bar',
3 => 'baz',
);
?>
If you want to check if the element 'foo' is in the array, you would do this
<?php
if(in_array('foo', $array)) {
// in array...
}else{
// not in array...
}
?>
If you want to get the array index of 'foo', you would do this:
<?php
$key = array_search('foo', $array);
?>
Also, a simple rule for the order of the arguments in these functions is: "needle, then haystack"; what you're looking for should be first, and what you're looking in second.

Categories