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);
?>
Related
I have an array with string value in PHP for example : arr['apple'], arr['banana'], and many more -about 20-30 data (get it from some process). Now I want to get its value and return it to one variable.
For example, I have Original array is like this:
$arr['Apple']
$arr['Banana']
and more..
and result that I want is like this:
$arr[0] = "Apple"
$arr[1] = "Banana"
and more..
Any idea how to do that?
Why not using array_keys()?
$new_array = array_keys($array);
Use array_flip()
$new_arr = array_flip($old_arr);
Demonstration
use foreach loop
foreach($arr as $key => $val){
$new_var[] = $key;
}
use array_keys function:
$keys = array_keys($arr);
It returns an array of all the keys in array.
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.
I a string that is coming from my database table say $needle.
If te needle is not in my array, then I want to add it to my array.
If it IS in my array then so long as it is in only twice, then I still
want to add it to my array (so three times will be the maximum)
In order to check to see is if $needle is in my $haystack array, do I
need to loop through the array with strpos() or is there a quicker method ?
There are many needles in the table so I start by looping through
the select result.
This is the schematic of what I am trying to do...
$haystack = array();
while( $row = mysql_fetch_assoc($result)) {
$needle = $row['data'];
$num = no. of times $needle is in $haystack // $haystack is an array
if ($num < 3 ) {
$$haystack[] = $needle; // hopfully this adds the needle
}
} // end while. Get next needle.
Does anyone know how do I do this bit:
$num = no. of times $needle is in $haystack
thanks
You can use array_count_values() to first generate a map containing the frequency for each value, and then only increment the value if the value count in the map was < 3, for instance:
$original_values_count = array_count_values($values);
foreach ($values as $value)
if ($original_values_count[$value] < 3)
$values[] = $value;
As looping cannot be completely avoided, I'd say it's a good idea to opt for using a native PHP function in terms of speed, compared to looping all values manually.
Did you mean array_count_values() to return the occurrences of all the unique values?
<?php
$a=array("Cat","Dog","Horse","Dog");
print_r(array_count_values($a));
?>
The output of the code above will be:
Array (
[Cat] => 1,
[Dog] => 2,
[Horse] => 1
)
There is also array_map() function, which applies given function to every element of array.
Maybe something like the following? Just changing Miek's code a little.
$haystack_count = array_count_values($haystack);
if ($haystack_count[$needle] < 3)
$haystack[] = $needle;
I have 2 arrays, the value will be loaded from database, below is an example:
$arr1 = array(1,2,3);
$arr2 = array(1,2,3,4,5,6,7);
What I want to do is to check if all the values in $arr1 exist in $arr2. The above example should be a TRUE while:
$arr3 = array(1,2,4,5,6,7);
comparing $arr1 with $arr3 will return a FALSE.
Normally I use in_array because I only need to check single value into an array. But in this case, in_array cannot be used. I'd like to see if there is a simple way to do the checking with a minimum looping.
UPDATE for clarification.
First array will be a set that contains unique values. Second array can contain duplicated values. They are both guaranteed an array before processing.
Use array_diff():
$arr1 = array(1,2,3);
$arr2 = array(1,2,3,4,5,6,7);
$arr3 = array_diff($arr1, $arr2);
if (count($arr3) == 0) {
// all of $arr1 is in $arr2
}
You can use array_intersect or array_diff:
$arr1 = array(1,2,3);
$arr2 = array(1,2,3,4,5,6,7);
if ( $arr1 == array_intersect($arr1, $arr2) ) {
// All elements of arr1 are in arr2
}
However, if you don't need to use the result of the intersection (which seems to be your case), it is more space and time efficient to use array_diff:
$arr1 = array(1,2,3);
$arr2 = array(1,2,3,4,5,6,7);
$diff = array_diff($arr1, $arr2);
if ( empty($diff) ) {
// All elements of arr1 are in arr2
}
You can try use the array_diff() function to find the difference between the two arrays, this might help you. I think to clarify you mean, all the values in the first array must be in the second array, but not the other way around.
In my particular case I needed to check if a pair of ids was processed before or not. So simple array_diff() did not work for me.
Instead I generated keys from ids sorted alphabetically and used them with in_array:
<?php
$pairs = array();
// ...
$pair = array($currentId, $id);
sort($pair);
$pair = implode('-', $pair);
if (in_array($pair, $pairs)) {
continue;
}
$pairs[$pair] = $pair;
This is probably not an optimum solution at all but I just needed it for a dirty script to be executed once.
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'));