I am working with PHP,I have array and i want to change position of array, i want to display matching value in first position,For example i have following array
$cars=('Toyota','Volvo','BMW');
And i have variable $car="BMW" And i want to match this variable with array and if match then this array value should be at first in array
so expected result is (matching record at first position)
$cars=('BMW','Volvo','Toyota');
How can i do this ?
You can use array_search and array_replace for this purpose. try below mentioned code
$cars=array(0 =>'Toyota',1 =>'Volvo',2 =>'BMW');
$car="BMW";
$resultIndex = array_search($car, $cars); //get index
if($resultIndex)
{
$replacement = array(0 =>$car,array_search($car, $cars)=>$cars[0]); //swap with 0 index
$cars = array_replace($cars, $replacement); //replace
}
print_r($cars);
This can be solved in one line with array_merge and array_unique array functions.
$cars=['Toyota','Volvo','BMW'];
$car="BMW";
$cars2 = array_unique(array_merge([$car],$cars));
//$cars2: array(3) { [0]=> string(3) "BMW" [1]=> string(6) "Toyota" [2]=> string(5) "Volvo" }
$car is always at the beginning of the new array due to array_merge. If $car already exists in the $cars array, array_unique will remove it. If $car is not present in the $cars array, it is added at the beginning. If this behavior is not desired, you can use in_array to test whether $car is also contained in the $cars array.
The simplest is to "sort" by "Value = BMW", "Value != BMW".
The function that sorts and resets the keys (i.e. starts the resulting array from 0, which you want) is usort (https://www.php.net/manual/en/function.usort.php)
So your comparison function will be If ($a == "BMW") return 1, elseif ($b == "BMW") return -1, else return 0; (Paraphrased, don't expect that to work exactly - need to leave a bit for you to do!)
Related
I have an array like this (PHP Code):
$my_arr=array(0=>"Joe",1=>"Mike",2=>"Simo","Peter"=>"35", 3=>"Ben" , "Ben"=>"37", 4=>"Nik" , "Joe"=>"43");
I want just get values specific range of index and replace previous arrays values with these new values.Something like this:
$rang= 0-4 OR 0,1,2,3,4 //range of index values.
$my_arr= filtered array value in range index of $range.
I want get this result:
$my_arr=array(0=>"Joe",1=>"Mike",2=>"Simo", 3=>"Ben" , 4=>"Nik");
How should I do this?
Update:
I just want to separate the values of the array($my_arr) that are within the range of the specified number of indexes and everywhere in the array and replace all previous array($my_arr) values with these new values.
**
If there were not some of the indexes, Other indexes outside of the specified range for index numbers should not be replaced and only return values of indexes between 0 and 4($my_arr[0]....$my_arr[4]) , and if they don't have value leave empty or do not return something else
array_slice
Extract a slice of the array
array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )
Since your array contains mixed keys, you should first sort it so the numeric keys would appear first.
According to your code:
ksort($my_arr, SORT_NATURAL);
$my_sliced_arr = array_slice($my_arr, 0, 4);
Output:
//var_dump($my_sliced_arr)
array(4) {
[0]=>
string(3) "Joe"
[1]=>
string(4) "Mike"
[2]=>
string(4) "Simo"
[3]=>
string(3) "Ben"
}
Manual array_slice
Manual ksort
I found a simple solution after several tests:
foreach($my_arr as $indx=>$val )
{
if(is_int($indx) && ($indx>=0 && $indx<=4))
{
$my_arr[$indx]= $val;
}
else
{ continue; }
}
Try this code
$my_arr=array(0=>"Joe",1=>"Mike",2=>"Simo","Peter"=>"35", 3=>"Ben" , "Ben"=>"37", 4=>"Nik" , "Joe"=>"43");
$numerickeys = array_filter(array_keys($my_arr), 'is_int');
foreach($numerickeys as $num)
{
$ar2[$num] = $my_arr[$num];
}
print_r($ar2);
I am trying to get the highest occurence in the array below using PHP, but there are 2 highest occurrences.
$cars = array('volvo', 'benz','honda','volvo','toyota', 'toyota');
I used the code below which works for a single result but when there are two highest occurrences, it outputs only one of the two.
$c = array_count_values($cars);
$val = array_search(max($c), $c);
How can I get the highest occurrences in an array even if there are two or more similar result?
For this, you can use array_keys with its optional 2nd argument:
$counts = array_count_values($cars);
$top = array_keys($counts, max($counts));
From the manual:
If the optional search_value [2nd argument] is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.
For the input given in the OP, the result is:
array(2) {
[0]=>
string(5) "volvo"
[1]=>
string(6) "toyota"
}
See it live on 3v4l.org.
I am having an issue with understanding why my array containing 3 elements must be sliced into 2 parts each. I wish to access a number I'm pushing into the array only however it seems to print out the index rather than the 'key' value I pushed into it ($number).
I have a 2d array I'm pushing an ID and an integer into, and then sort it :
$array = [[]];
array_push($array, $doc[_id], $number);
array_multisort($array);
I then filter any empty elements:
$array = array_filter($array); //remove null elements
This all works as id expect however the array looks like this by this point:
unrated.array(5)
{
[2]=> object(MongoId)#32 (1)
{ ["$id"]=> string(24) "57b99696ce2350100b000029" }
[3]=> object(MongoId)#31 (1)
{ ["$id"]=> string(24) "57b998ccce2350181700002b" }
[4]=> object(MongoId)#33 (1)
{ ["$id"]=> string(24) "57b99a84ce2350100b00002b" }
[5]=> int(2) [6]=> int(3)
}
Again, this is fine however it means when I loop over the array using the code below it appears to be longer than 3 elements, as I have to slice from 0-6 instead of 0-3:
$array = array_slice($array, 0, 6, true); //only get 3 elements from array
foreach ($array as $key => $value) {
echo $key; //prints out values from 1-5 weirdly.... should just print the $number value
$id = $value->{'$id'};
}
What I am trying to achieve is to find the element in the array with the lowest possible value that was pushed earlier (array_push($array, $doc[_id], $number);) however because I cannot understand why the array is split into 6 rather than 3 parts its even more confusing.
Question in short : How do I access the $number pushed into the array and why is my array 6 seemingly 6 in size when it contains only 3 elements.
Any help would be appreciated, thanks.
To be clear, array_push simply pushes one or more values onto the end of an array. The first argument of array_push is the array you wish to push the value(s) to, and any subsequent argument is a list of values you wish to push. So what you're doing with array_push($array, $doc[_id], $number) is pushing two values ($doc[_id] and $number) to the end of the array $array. array_push will just use the next available index as the key when it adds those values to the array. It will not allow you to specify a key. This is the same thing as doing $array[] = $value.
To specify a key you must assign a value directly to the array key like so: $array[$key] = $value.
I'm trying to remove specific element from php array with unset function. Problem is that when I var_dump array it shows all indexes (not good) but If I try to var_dump specific index PHP throws warning (good).
$a = [
'unset_me',
'leave_me',
'whatever',
];
unset($a['unset_me']);
var_dump($a);
/**
array(3) {
[0]=>
string(8) "unset_me"
[1]=>
string(8) "leave_me"
[2]=>
string(8) "whatever
*/
var_dump($a['unset_me']); // Undefined index: unset_me
Question is why php behave like this and how to remove index properly?
One more solution:
$arr = array('unset_me','leave_me','whatever',);
print_r($arr);
// remove the elements that you want
$arr = array_diff($arr, array("unset_me"));
print_r($arr);
You can try this with array_search -
unset($a[array_search('unset_me', $a)]);
If needed then add the checks like -
if(array_search('unset_me', $a) !== false) {
unset($a[array_search('unset_me', $a)]);
}
Demo
$arr = array('unset_me','leave_me','whatever',);
print_r($arr);
echo '<br/>';
$key = array_search('unset_me', $arr);
if($key !== false)
unset($arr[$key]);
print_r($arr);
I recently encountered this problem and found this solution helped:
unset($a[array_flip($a)['unset_me']]);
Just to explain what is going on here:
array_flip($a) switches the items for the key. So it would become:
$a = [
'unset_me' => 0,
'leave_me' => 1,
'whatever' => 2,
];
array_flip($a)['unset_me'] therefore resolves to being 0. So that expression is put into the original $a which can then be unset.
2 caveats here:
This would only work for your basic array, if you had an array of objects or arrays, then you would need to choose one of the other solutions
The key that you remove will be missing from the array, so in this case, there will not be an item at 0 and the array would start from 1. If it is important to you, you can do array_values($a) to reset the keys.
I'm comparing the results of two exploded strings (results from a query), though when I use array_intersect to find the overlap of the arrays, I unfortunately only receive the overlap of those tags which are come first in each array...so for example if two arrays look like this:
Array1:
array(
[0]=> tag_a
[1]=> tag_b
)
Array2:
array(
[0]=> tag_a
[1]=> tag_b
)
Array_Intersect is only returning tag_a as a match. I expected the behavior of array_intersect to return tag_a as well as tab_b.
As you can see later in my code, I'm then using the matches (tags present in both arrays) to build the array contactarray. I'm able to build the array OK, it just doesn't contain the values I would have expected (ex: tag_b).
EDIT I've run several tests printing the contactarray and have applied various tag strings to those contacts and only the contacts who have have tag_a first (in the array) are being returned even though several other contacts have tag_a, though it's just not first in the array.
Thoughts?
if ($frequency == 'Weekly')
{
$data['query_tag'] = $this->db->get('tags');
foreach ($data['query_tag']->result() as $row2)
{
$contact_tags = $row2->tags;
$contact_tags_exploded = explode(",", $contact_tags);
$rule_tags_exploded = explode(",", $rule_tags);
$result = array_intersect($rule_tags_exploded, $contact_tags_exploded);
if(isset($result) && count($result) != 0){
$contactarray[] = $row2->contact_name;
}
}
}
Try array_uintersect()
Here $arr1 is your 1st array and $arr2 is second array
$intersect = array_uintersect($arr1, $arr2, 'compareDeepValue');
print_r($intersect);
function compareDeepValue($val1, $val2)
{
return strcmp($val1['value'], $val2['value']);
}
This should give you both the values
Not Sure where is the problem you are facing copy paste this code and you will see the two values properly.
$arr = array( 'tag_a','tab_b ');
$arr = array('tag_a','tab_b ');
print_r(array_intersect($arr, $arr));
use master array for first argument and array to compare as second argument.
I am not sure what problem you have.