I have an associative array, $teams_name_points. The length of the array is unknown.
How do I access the first and forth value without knowing the key of this array in the easiest way?
The array is filled like this:
$name1 = "some_name1";
$name2 = "some_name2";
$teams_name_points[$name1] = 1;
$teams_name_points[$name2] = 2;
etc.
I want to do something like I do with an indexed array:
for($x=0; $x<count($teams_name_points); $x++){
echo $teams_name_points[$x];
}
How do I do this?
use array_keys?
$keys = array_keys($your_array);
echo $your_array[$keys[0]]; // 1st key
echo $your_array[$keys[3]]; // 4th key
You can use array_values which will give you a numerically indexed array.
$val = array_values($arr);
$first = $val[0];
$fourth = $val[3]
In addition to the array_values, to loop through as you show:
foreach($teams_name_points as $key => $value) {
echo "$key = $value";
}
You can get use the array_keys function such as
//Get all array keys in array
$keys = array_keys($teams_name_points);
//Now get the value for 4th key
//4 = (4-1) --> 3
$value = $teams_name_points[$keys[3]];
You can get all values now as exists
$cnt = count($keys);
if($cnt>0)
{
for($i=0;$i<$cnt;$i++)
{
//Get the value
$value = $team_name_points[$keys[$i]];
}
}
Related
The dump of the following array is:
$quest_all = $qwinners->pluck('id', 'qcounter')->toArray();
array(2) { [60]=> int(116) [50]=> int(117) }
As shown above, the key is 60 and 50 (which is qcounter), while the value is 116 and 117 (which is id).
I'm trying to assign the qcounter to a variable as follows, but with a fixed index, such as 0,1,2,3 .. etc :
$qcounter1= $quest_all[0];
$qcounter2= $quest_all[1];
And the same with id :
$id1= $quest_all[0];
$id2= $quest_all[1];
Any help is appreciated.
Try as below:
One way is:
array_values($quest_all); will give you an array of all Ids
array_keys($quest_all); will give an array of all qcounters and respective indexes for qcounter and ids will be the same.
Other way, First get all qcounters only from collection:
$quest_all = $qwinners->pluck('qcounter')->toArray();
$qcounter1= $quest_all[0];
$qcounter2= $quest_all[1];
...
and so on
Then get all ids
$quest_all = $qwinners->pluck('id')->toArray();
$id1= $quest_all[0];
$id2= $quest_all[1];
...
and so on
You can also use foreach to iterate through the result array.
To reset array keys, use array_values().
To get array keys, use array_keys():
$quest_all = $qwinners->pluck('id', 'qcounter')->toArray();
$quest_all_keys = array_keys($quest_all);
$quest_all_values = array_values($quest_all);
Or simply use foreach():
$keys = [];
$values = [];
foreach($quest_all as $key => $value){
$keys[] = $key;
$values[] = $value;
}
I am not sure why you want variable names incrementing when you could have an array instead but if you don't mind an underscore, '_' in the name and them starting at 0 index you can use extract to create these variables. (As an exercise)
$quest_all = ...;
$count = extract(array_keys($quest_all), EXTRA_PREFIX_ALL, 'qcounter');
extract(array_values($quest_all), EXTRA_PREFIX_ALL, 'id');
// $qcounter_0 $qcounter_1
// $id_0 $id_1
for ($i = 0; $i < $count; $i++) {
echo ${'qcounter_'. $i} .' is '. ${'id_'. $i} ."\n";
}
It would probably be easier to just have the 2 arrays:
$keys = array_keys($quest_all);
$values = array_values($quest_all);
I have 2 SELECT statement in my PHP. Both the select statements fetch data from two different DB. The fetched data is saved in PDO Assoc Array. The problem is when I want to compare those two arrays to find that if the column 'id' exist in both arrays or not. If it exists then ignore it. If it's a unique id then save it into a third array. But I found some problems in my Logic Below
And after running the below code I am getting a couple of error:
1: Array to string conversion
2: duplicate key value violates unique constraint
$arr1 = $msql->fetchAll(PDO::FETCH_ASSOC);
$array1 = array();
foreach($arr1 as $x){
$array1[] = $x['id'];
}
$arr2 = $psql->fetechAll(PDO::FETCH_ASSOC);
$array2 = array();
foreach($arr2 as $y){
$array2[] = $y['id'];
}
$finalarray = array();
for ($i = 0; $i < count($arr1); $i++){
if(count(array_intersect($array1,$array2)) <= 1){// is the count of id is 1 or less save that whole row in the $finalarray
$finalarray = $arr1[$i]; // saving the unique row.
}
else{
continue;
}
}
All I am trying to get the unique row of data array() after comparing their id column.
You can use in_array() function as both arrays are index array.
$finalarray = array();
for ($i = 0; $i < count($arr1); $i++){
if(count(array_intersect($array1,$array2)) <= 1){// is the count of id is 1 or less save that whole row in the $finalarray
$finalarray = $arr1[$i]; // saving the unique row.
}
else{
continue;
}
}
make change in code:
$finalarray = array();
for ($i = 0; $i < count($arr1); $i++){
if(!in_array($array1[$i], $array2)){
$finalarray[] = $array1[$i]; // saving the unique row.
}
}
You can simply use array_intersect() to get common values between two array. for difference, can use array_diff()
$array1 = [1,2,3,4,5,6,7];
$array2 = [2,4,6];
//array_intersect — Computes the intersection of arrays
$result = array_intersect($array1, $array2);
print_r($result);
//array_diff — Computes the difference of arrays
$result = array_diff($array1, $array2);
print_r($result);
DEMO
Rather than using 3 different arrays to get unique ids, you can do it by using one array. Make changes to your code as below:
$finalarray = array();
$arr1 = $msql->fetchAll(PDO::FETCH_ASSOC);
foreach($arr1 as $x){
if (!in_array($x['id'],$finalarray)) { // check id is already stored or not
$finalarray[] = $x['id'];
}
}
$arr2 = $psql->fetechAll(PDO::FETCH_ASSOC);
foreach($arr2 as $y){
if (!in_array($y['id'],$finalarray)) { // check id is already stored or not
$finalarray[] = $y['id'];
}
}
Maybe you should make sure which array is larger before your loop ;
Or using array_diff:
$finalarray = array_diff($array1 , $array2) ?? [];
$finalarray = array_merge( array_diff($array2 , $array1) ?? [], $finalarray );
I have an array which contain value string value and null value.. I want to count all element who assigned string value.
$items = array('name'=>'abc','contact'=>'0177....','address'=>'','country'='')
expected result:
$items = array('name'=>'abc','contact'=>'0177....')
and count new array element $items
I want to convert actual array
and count element of newly created array
Need to simply use array_filter and store it within some variable like as
$items = array('name'=>'abc','contact'=>'0177','address'=>'','country'=>'');
$filtered_arr = array_filter($items);
echo count($filtered_arr);
print_r($filtered_arr);
You need to use array_filter() here.
echo count(array_filter($items));
Try this
<?php
$result = array();
$items = array('name'=>'abc','contact'=>'0177....','address'=>'','country'=>'');
foreach($items as $key => $item)
{
if($item != '')
array_push($result, $item);
}
echo "Count ".count($result);
?>
OR
$items = array('name'=>'abc','contact'=>'0177','address'=>'','country'=>'');
$result = array_filter($items);
echo "Count".count($result);
I need to remove all elements in the array that comes after the FIRST instance of an element that matches same string value before the dot. ie, not taking into consideration any values after the .
from
$array = ("ItemNew1.1", "Item2.0", "Item3Test.0", "Item2.2", "Item4.4", "Item2.5")
to
$array = ("ItemNew1.1", "Item2.0", "Item3Test.0", "Item4.4")
The code below creates a temp array to hold the values that are already in the array, it runs a foreach on the original array and if the value is not in the temporary array, it inserts it into a new array
$tempArray = array();
$newArray = array();
foreach($array as $value) {
list($item, ) = explode(".", $value);
$int = filter_var($item, FILTER_SANITIZE_NUMBER_INT);
if(!in_array($int, $tempArray)) {
$newArray[] = $value;
$tempArray[] = $int;
}
}
Now, $newArray is the array that you want.
DEMO
I have two arrays:
$array1 = array(1=>1,10=>1,12=>0,13=>13);
$array2 = array(1=>"Hello",10=>"Test",12=>"check",13=>"error");
Here $array1 has keys and values. Now I want to take the first value from $array1(as 1) and I want to check if this is repeated in this array .
Here 1 is repeated two times so I want to take the two keys 1,10 and display the corresponding values of these keys from $array2. If the value in $array1 is not repeated then I want to just display the value of this key from $array2.
I want to get the output as follows:
Hello Test
check
error
That means in $array1 1,10 keys have the same value so the value of 1 and the value of 10 from $array2 is merged then displayed.
Like 12 has 0 this is not repeated so simply take value of 12 from $array2.
Like 13.
How can I do this?
<?php
$array1 = array(1=>1,10=>1,12=>0,13=>13);
$array2 = array(1=>"Hello",10=>"Test",12=>"check",13=>"error");
$groupedKeys = array();
foreach($array1 as $key=>$arr){
$groupedKeys[$arr][] = $key;
}
foreach($groupedKeys as $key => $groupedKeyArr){
foreach($groupedKeyArr as $groupedKey){
echo $array2[$groupedKey];
}
echo "<br /> ";
}
?>
http://codepad.org/9R9s5lTM
There is a built in function that returns an array with the number of times a value is repeated http://php.net/manual/en/function.array-count-values.php
This is really rough, but a simple way of doing it could be:
<?
$array1 = array(1=>1,10=>1,12=>0,13=>13);
$array2 = array(1=>"Hello",10=>"Test",12=>"check",13=>"error");
$prev = $array1[1];
foreach($array1 as $key => $val)
{
if($val != $prev && $key != 1)
{
echo '<br />';
}
echo $array2[$key].' ';
$prev = $val;
}
?>
Example: http://codepad.org/OpLdtStp
This assumes that you're first key is always going to be 1 by the way.
I am providing you a function returns an array with the number of times a value is repeated in an array(as values) and values as the keys. Further task is not difficult.
function check_number_of_times_elements_occur_in_array($a)//returns values of array as keys, associating values being their total occurences in the array
{
$r=array();
foreach($a as $v)
++$r[$v];
return $r;
}
I think this will do for you..
function test($array1,$array2) {
$repeated_values = array_count_values($array1);
foreach($repeated_values as $key => $value){
if($value > 1) {
foreach($array1 as $key1 => $value1){
if($key == $value1){
$repeated_values_keys[] = $key1;
}
}
}
}
$str_top = "";
foreach($repeated_values_keys as $k){
$str_top .= $array2[$k]." ";
}
echo $str_top.'<br/>';
foreach($array2 as $key2 => $value){
if(!in_array($key2,$repeated_values_keys)){
echo $value.'<br/>';
}
}
}