Compare array key, if true display the value PHP - php

I'm trying to compare the array key with another array, and if they are the same, I need to display the value of that key.
This is my array.
$events = array( 0 => var1,
1 => var2,
2 => var3
);
Lets assume that the $get_date is the key and the $get_name is the value, I want to compare the $get_date to another value, IF TRUE, it will display the value of the combine array. Just ignore the array_combine, they still have the same output anyway. Ignore also the variable used.
$events = array_combine($get_date, $get_name);
for($i=0; $i<=5; $i++)
{
/* this is where I want the comparing to be done.
/* this is the confusing part. Not sure what to do.
}

Try using array_key_exists
$result =array();
for($i=0; $i<=5; $i++){
if (array_key_exists($i, $events)) {
$result[] = $events[$i];
}
}
See demo here

Related

Check if all arrays inside an array have a specific key

Example array:
$items = array(
array('sort': 1, 'name': 'name'),
array('sort': 3, 'name': 'name'),
array('sort': null, 'name': 'name')
);
I need to know if all child arrays have the sort key. If not, I'd manually create the sort via a for loop (and over-write the sort value for the ones that have it).
I'm already running a for loop, and I was thinking of adding another key such as manual_sort which I would equal to index + 1, and after the loop, if at least 1 array didn't have the sort key or if it's null), I'd use the manual_sort instead of the sort key (for example when looping the elements via the front-end or whatever usage the data has).
Also thought about doing a second loop to know whether or not sort should be overwritten.
These seems like dirty solutions though, any ideas?
My current code looks something like:
$db_sorted_items = true;
for ($i=0; $i < count($items); $i++) {
$items[$i]['name'] = ucfirst($items[$i]['name']);
if (empty($items[$i]['sort']) {
$db_sorted_items = false;
}
$items[$i]['number'] = $i + 1; // $i+1 because sort number starts at 1.
}
// err, gotta use `$items[$i]['number']` (or `sort` had all arrays had a positive `sort` key)
// use array_column to get array for key 'sort'
// then use array_filter to remove null values
// then compare count
if(count($array) == count(array_filter(array_column($array,'sort')))){
echo 'All have valid sort key';
}else{
echo 'No, few are missing';
}
In case if you want to have strict check, to make sure value corresponding to key sort is numeric then you may use below one, using is_numeric
if(count($array)==count(array_filter(array_column($array,'sort'),'is_numeric'))){
}
Your code looks good to me. I'd change it so it refreshes all sort attributes if it finds one object that doesn't have it, like this:
$db_sorted_items = true;
for ($i=0; $i < count($items); $i++) {
$items[$i]['name'] = ucfirst($items[$i]['name']);
if ($db_sorted_items && empty($items[$i]['sort']) {
$db_sorted_items = false;
$i = -1; // Re-start for (the for will add 1 at the end)
}else{
$items[$i]['sort'] = $i + 1; // $i+1 because sort number starts at 1.
}
}

How I can show only three elements of my associative array using for?

This is my Associative Array:
$vetor = array(
"Name"=> "myName",
"Tel"=> "555-2020",
"Age"=> "60",
"Gender"=> "Male"
);
How I can show only three elements using the loop for?
I tried this:
for($i=0; $i<=2; $i++){
echo $vetor[$i]."<br>";
}
But without success. How I can do this?
You referring to wrong indexes because to reference the first element on your array you have to do something like : $vetor["Name"] instead of $vetor[0]
$i = 0;
foreach($vetor as $key => $value){
if($i == 2){ break; }
echo $value;
$i++;
}
foreach makes more sense for an array like this, but if you want to use for for whatever reason, the problem you'll have is that the array doesn't have sequential numeric indexes that correspond to your loop increment variable. But there are other ways to iterate over the first three elements without knowing what the indexes are.
// this first step may not be necessary depending on what's happened to the the array so far
reset($vetor);
$times = min(3, count($vetor));
for ($i = 0; $i < $times; $i++) {
echo current($vetor).'<br>';
next($vetor);
}
If next moves the internal array pointer beyond the last array element, current($vetor) will return false, so setting $times using min with the number of times you want and the array count will prevent you from looping more times than there are items in the array.
Another way, if you don't care what the keys are, is to use array_values to convert the array keys to numbers.
$vetor = array_values($vetor);
for ($i=0; $i < 3; $i++) {
echo $vetor[$i].'<br>';
}

How to rewrite array value?

I have an array inside another and I would like to change a value in a key.
//Obtenemos el numero de arrays
$count = array();
for($i = 0; $i < count($passer); $i++)
{
if(array_key_exists($passer[1],$passer[$i])) {
$passer[1] = "hola";
}
$count[] = $passer[$i];
}
//return....
return $count;
I need to change entries where the key is 1 and replace the value.
I have this array output:
array
(
[0]=>array
(
[0]=>81278
[1]=>87364
[2]=>34923
)
[1]=>array
(
[0]=>81278
[1]=>87364
[2]=>34923
)
)
but I get an error:
Warning: array_key_exists() [function.array-key-exists]:
Any idea what this means and what to do about it?
Several things you should change. First of all the way you write your for statement isn't optimal, it will execute the count() function upon every iteration, make it like so
for($i = 0, $c = count($passer); $i < $c; $i++)
Second, your problem. You need to check the key, which in your case is static 1, in the array $passer[$i], so your array_key_exists() function should look like this
array_key_exists(1,$passer[$i])
array_key_exists expects the first parameter to be the key and second the array you wish to inspect
I think you meant to put array_key_exists($passer[1], $passer)
The second parameter has to be an array, but in your example you are passing it the element of an array (which is not an array hence the php warning).
http://php.net/manual/en/function.array-key-exists.php

php arrays get the order number of a certain element

Lets say i have an array in PHP
$test['michael_unique_id'] = 3;
$test['john_unique_id'] = 8;
$test['mary_unique_id'] = 10;
.
.
.
.
$test['jimmy_unique_id'] = 4;
(the values (3,8,10.........4) are unique)
Lets say i want to search for the unique id 10, and get the order of the matching element in the array. In this example, the third element has the value 10, so i should get the number 3.
I can do it by scanning with a for loop looking for the value i'm searching and then get the $i value when i have a match, but i wonder if there is any built-in function (or a better method) that implements this.
You can get all of the array's values as an array with array_values() and then use array_search() to get the position (offset) of that value in the array.
$uniq_id = 10;
$all_vals = array_values($test); // => array(3, 8, 10, ... )
echo array_search( $uniq_id, $all_vals ); // => 2
Because PHP array indices are zero-based, you'll get 0 for the first item, 1 for the second item, etc. If you want the first item to be "1," then just add one. All together now:
$uniq_id = 10;
echo array_search( $uniq_id, array_values( $test ) ) + 1; // => 3
It's not clear to me, however, that this is necessarily as performant as just doing a foreach:
$uniq_id = 10;
$idx = 1;
foreach($test as $val) {
if($val == $uniq_id) {
break;
}
$idx++;
}
echo $idx; // => 3
Well, array_search will give you the key, but in your case, you want the index of that key, so I believe a loop is your best bet. Is there a good reason why you need the index? It doesn't seem very useful to me.

Efficient algorithm for detecting matches

I'm looking for an efficient algorithm for detecting equal values in an array of integers N size. It must return the indices of the matches.
Alas, I can't think of anything more clever then brute force with two loops.
Any help will be appreciated.
Thanks!
You could intersect the array. This finds all the values of array2 that are in array1
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result_array = array_intersect_assoc($array1, $array2);
print_r($result_array);
Would return
Array
(
[a] => green
)
It returns an array with all of the keys and values of the matches. Basically you can provide an infinite number of arguments to the array_insert_assoc:
array_intersect_assoc($base_array, $arr1, $arr2 ...);
It will search $base_array for the values that are in all the subsequent arrays. That means that the key and value will be taken from the $base_array
You could also compare the keys by using:
array_intersect_keys($base_array, $arr1, $arr2, $arr3);
These loops are O(N^2). Is N big? If so, can you sort the array O(NlogN), then scan it O(N)? ... or am I missing something?
You can use a set to hold the recent values. For example,
results = empty list
set = empty set
foreach key, val in array:
if val is not in set: add val to set
else: add key to results
return results
Each look up of set is O(1), so this algo will results in O(n) instead of O(n^2) if nested-loop is used.
In case you want to keep track of multi-occurence like this array 1, 2, 3, 3, 2, 1 you can use a hash table with key is the value and value (of the corresponding key in table) is the list of indices. The result for the given array will look lik {1:0, 5; 2: 1, 4; 3: 2, 3}.
results = empty hashtable
for each key, val in array:
if val is not in results:
results[val] = new list()
results[val].append(key)
return results
Perhaps this?
$arr = array_map('unserialize', array_unique(array_map('serialize', $arr)));
From the question: How to remove duplicated 2-dimension array in PHP?
if ($arr !== array_map('unserialize', array_unique(array_map('serialize', $arr))))
{
// found duplicates
}
You don't have to go through all the array again for each element. Only test an element with the subsequent element in the array:
$array = /* huge array */;
$size = count($array);
for($i = 0; $i < $size; $i++)
{
for($j = $i + 1; $j < $size; $j++) // only test with the elements after $i
{
if($array[$i] == $array[$j])
return true; // found a duplicate
}
return false; // found no duplicate
}
That's the most efficient way I can think of. Adapt it to your need as you will.
If one of your arrays is reasonably static (that is you are comparing to the same array several times ) you could invert it.
That is set up another array which is keyed by value and returns the index into the real array.
$invert = array();
foreach ($cmptoarray as $ix => $ival) {
$invert[$ival] = $ix;
}
Then you simply need an if ( isset($invert[$compfrmarray[$i]) ) .... to check the number.
Note: this is only worth doing if you compare against the same array several times!
Just use an associative array mapping a value to its index:
foreach($array1 as $index => $value) {
$aa[$value] = $index;
}
foreach($array2 as $index => $value) {
if(isset($aa[$value])) {
echo 'Duplicate: . Index 1: '.$aa[$value].' Index 2: '.$index.'.';
}
}

Categories