First time trying to find something in an array using an array as both a needle and a haystack. So, example of 2 arrays:
My Dynamically formed array:
Array (
[0] =>
[1] => zpp
[2] => enroll
)
My Static comparison array:
Array (
[0] => enroll
)
And my in_array() if statement:
if (in_array($location_split, $this->_acceptable)) {
echo 'found';
}
$location_split; // is my dynamic
$this->_acceptable // is my static
But from this found is not printed out, as I'd expect it to be? What exactly am I failing on here?
If i'm understanding you right, you want to see whether the first array's entries are present in the second array.
You might look at array_intersect, which would return you an array of stuff that's present in all the arrays you pass it.
$common = array_intersect($this->_acceptable, $location_split);
if (count($common)) {
echo 'found';
}
If the count of that array is at least 1, then there's at least one element in common. If it's equal to your dynamic array's length, and the array's values are distinct, then they're all in there.
And, of course, the array will be able to tell you which values matched.
Because there is no element in your array containing array('enroll') in it (only 'enroll').
Your best bet would be to use array_diff(), if the result is the same as the original array, no match is found.
You are interchanging the parameters for in_array (needle & haystack). It needs to be,
if(in_array($this->_acceptable, $location_split))
{
echo 'found';
}
Edit: Try using array_intersect.
Demo
Related
Question has been updated to clarify
For simple arrays, I find it convenient to use $arr[$key]++ to either populate a new element or increment an existing element. For example, counting the number of fruits, $arr['apple']++ will create the array element $arr('apple'=>1) the first time "apple" is encountered. Subsequent iterations will merely increment the value for "apple". There is no need to add code to check to see if the key "apple" already exists.
I am populating an array of arrays, and want to achieve a similar "one-liner" as in the example above in an element of the nested array.
$stats is the array. Each element in $stats is another array with 2 keys ("name" and "count")
I want to be able to push an array into $stats - if the key already exists, merely increment the "count" value. If it doesn't exist, create a new element array and set the count to 1. And doing this in one line, just like the example above for a simple array.
In code, this would look something like (but does not work):
$stats[$key] = array('name'=>$name,'count'=>++);
or
$stats[$key] = array('name'=>$name,++);
Looking for ideas on how to achieve this without the need to check if the element already exists.
Background:
I am cycling through an array of objects, looking at the "data" element in each one. Here is a snip from the array:
[1] => stdClass Object
(
[to] => stdClass Object
(
[data] => Array
(
[0] => stdClass Object
(
[name] => foobar
[id] => 1234
)
)
)
I would like to count the occurrences of "id" and correlate it to "name". ("id" and "name" are unique combinations - ex. name="foobar" will always have an id=1234)
i.e.
id name count
1234 foobar 55
6789 raboof 99
I'm using an array of arrays at the moment, $stats, to capture the information (I am def. open to other implementations. I looked into array_unique but my original data is deep inside arrays & objects).
The first time I encounter "id" (ex. 1234), I'll create a new array in $stats, and set the count to 1. For subsequent hits (ex: id=1234), I just want to increment count.
For one dimensional arrays, $arr[$obj->id]++ works fine, but I can't figure out how to push/increment for array of arrays. How can I push/increment in one line for multi-dimensional arrays?
Thanks in advance.
$stats = array();
foreach ($dataArray as $element) {
$obj = $element->to->data[0];
// this next line does not meet my needs, it's just to demonstrate the structure of the array
$stats[$obj->id] = array('name'=>$obj->name,'count'=>1);
// this next line obviously does not work, it's what I need to get working
$stats[$obj->id] = array('name'=>$obj->name,'count'=>++);
}
Try checking to see if your array has that value populated, if it's populated then build on that value, otherwise set a default value.
$stats = array();
foreach ($dataArray as $element) {
$obj = $element->to->data[0];
if (!isset($stats[$obj->id])) { // conditionally create array
$stats[$obj->id] = array('name'=>$obj->name,'count'=> 0);
}
$stats[$obj->id]['count']++; // increment count
}
$obj = $element->to->data is again an array. If I understand your question correctly, you would want to loop through $element->to->data as well. So your code now becomes:
$stats = array();
foreach ($dataArray as $element) {
$toArray = $element->to->data[0];
foreach($toArray as $toElement) {
// check if the key was already created or not
if(isset($stats[$toElement->id])) {
$stats[$toElement->id]['count']++;
}
else {
$stats[$toElement->id] = array('name'=>$toArray->name,'count'=>1);
}
}
}
Update:
Considering performance benchmarks, isset() is lot more faster than array_key_exists (but it returns false even if the value is null! In that case consider using isset() || array_key exists() together.
Reference: http://php.net/manual/en/function.array-key-exists.php#107786
I have an array that is associative that I have decoded from a json json_decode second value true and looks like
Array (
[test] => Array
(
[start] => 1358766000
[end] => 1358775000
[start_day] => 21
[end_day] => 21
)
)
But for some reason when I do $array[0] I get null? How can I get the array by index? Not by key name?
array_values() will give you all the values in an array with keys renumbered from 0.
The first level of the array is not numerical, it's an associative array. You need to do:
$array['test']['start']
Alternatively, to get the first element:
reset($array);
$first_key = key($array);
print_r($array[$first_key]);
You could use current.
$first = current($array); // get the first element (in your case, 'test')
var_dump($first);
This is by design . . . your JSON used a key (apparently test), which contained a JSON object. The keys are preserved when you do a json_decode. You can't access by index, though you could loop through the whole thing using a foreach.
From your comment, it sounds like you want to access previous and next elements from an associative array. I don't know a way to do this directly, but a hackish way would be as follows:
$testArr = array('a'=>'10', 'b'=>'2', 'c'=>'4');
// get numeric index of the element of interest
$keys = array_keys($testArr);
$i = array_search('b', $keys);
// get key of next element
$nextElementKey = $keys[$i+1];
// next element value
$nextElementValue = $testArry[$nextElementKey];
// get key of previous element
$prevElementKey = $keys[$i-1];
// prev value
$[prevElementValue = $testArry[$prevElementKey];
You'd probably want to add some error checking around the previous and next key calculations to handle the first and last values.
If you don't care about the data in the key, Ignacio's solution using array_keys is much more efficient.
I have an array like this one
$state[1]='FG';
$state[2]='BU';
$state[3]='CA';
...
$state[150]='YT'
What I need is to have the $state array ordered from A to Z and maintain, in some structure, the original order of the array.
Something like:
$state_ordered['BU']=2;
$state_ordered['CA']=3;
and so on.
I have the array in the first form in an include file: which is the most performant way and which is the related structure to use in order to have the best solution?
The include is done at each homepage opening...
Thanks in advance,
A.
Well, you can array_flip the array, thus making 'values' be the original indexes, and then sort it by keys...
$b = array_flip($a);
ksort($b);
then work with $b keys , but the values reflect original order
You want array_flip(), which switches the key and value pairs.
Example #2 from the link:
$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
Outputs:
Array
(
[1] => b
[2] => c
)
PHP has quite a few functions for sorting arrays. You could sort your array alphabetically by the values it holds by using asort() and then retrieve the index using array_search()
as such:
?php
$state[1]='FG';
$state[2]='BU';
$state[3]='CA';
asort($state);
$key = array_search('BU',$state);
print $state[$key] . PHP_EOL;
print_r($state);
this will output
BU
Array
(
[2] => BU
[3] => CA
[1] => FG
)
which as you can see keeps the original index values of your array. This does mean however that when you loop over your array without using the index directly, like when you use foreach that you then loop over it in the resorted order:
foreach($state as $key=>$value){
print "$key: $value" . PHP_EOL;
}
2: BU
3: CA
1: FG
You'd need to use ksort on the array first to sort it by index again before getting the regular foreach behaviour that you'd probably want/expect.
ksort($state);
foreach($state as $key=>$value){
print "$key: $value" . PHP_EOL;
}
1: FG
2: BU
3: CA
Looping using a for structure with numeric index values always works correcty of course. Be warned that these functions get passed your array by reference, meaning that they work on the 'live array' and not on a copy, you'll need to make your own copy first if you want one, more info in References Explained.
I have this array:-
Array ( [0] => Prefectorial Board/Prefect/2011 [1] => Prefectorial Board/Head Prefect/2011 [2] => Class Positions/Head Prefect/2011 [3] => Prefectorial Board/Head Prefect/2011 )
How to detect this array have duplicate value and I want the participant to re-fill in his data.
I have try to use this method to detect:-
$max = max(array_values($lr_str));
$keys = array_keys($lr_str, $max);
but it seem like not work for me.
any idea on this?
thanks for advance.
I do not know if I understand you correctly, but you can test the array has duplicated values by using this:
if (count($your_array) === count(array_unique($your_array)) {
// array has no duplicated values
} else {
// array has duplicated values - see compared arrays
}
Are you looking for array_unique?
You can use array_unique() to remove duplicate values. If no values were removed then the returned array should have the same number of items as the original:
if(count($lr_str) == count(array_unique($lr_str))){
//tell participant to re=fill their data
}
i have two arrays i.e$ar1=array("Mobile","shop","software","hardware");and$arr2=arry("shop","Mobile","shop","software","shop")
i want to compare the elements of arr2 to arr1 i.e
foreach($arr2 as $val)
{
if(in_array($val, $arr1))
{
//mycode to insert data into mysql table
variable++; // here there should be a variable that must be increamented when ever match found in $arr2 so that it can be saved into another table.
}
$query="update table set shop='$variable',Mobile='$variable'.......";
}
the $variable should be an integer value so that for later use i can use this variable(shop i.e in this example its value should be 3) to find the match.
My question is how can i get the variable that will increamented each time match found.
Sorry, I don't fully understand the purpose of your code. You can use array_intersect to get common values and array_diff to get the unique values when comparing two arrays.
i want to compare the elements of arr2 to arr1 i.e
Then you are essentially doing the same search for shop three times. It's inefficient. Why not sort and eliminate duplicates first?
Other issues. You are comparing arr2 values with the ones in arr1, which means the number of repetation for "shop" will not be 3 it will be one. Doing the opposite might give you the number of repetation of arr1[1] in arr2 =3.
There are multitude of ways to solve this problem. If efficiency is required,you might wish to sort so you don't have to go beyond a certain point (say s). You can learn to use indexes. Infact the whole datastructure is revolved around these kinds of things - from quick and dirty to efficient.
Not sure I understand the connection between your two arrays. But you can use this to count how many items are in your second array:
$items = array("shop","Mobile","shop","software","shop");
$count = array();
foreach($items as $item)
{
if(isset($count[$item]))
{
$count[$item]++;
}
else
{
$count[$item] = 1;
}
}
print_r($count); // Array ( [shop] => 3 [Mobile] => 1 [software] => 1 )