I have an array where I store key-value pair only when the value is not null. I'd like to know how to retrieve keys in the array?
<?php
$pArray = Array();
if(!is_null($params['Name']))
$pArray["Name"] = $params['Name'];
if(!is_null($params['Age']))
$pArray["Age"] = $params['Age'];
if(!is_null($params['Salary']))
$pArray["Salary"] = $params['Salary'];
if(count($pArray) > 0)
{
//Loop through the array and get the key on by one ...
}
?>
Thanks for helping
PHP's foreach loop has operators that allow you to loop over Key/Value pairs. Very handy:
foreach ($pArray as $key => $value)
{
print $key
}
//if you wanted to just pick the first key i would do this:
foreach ($pArray as $key => $value)
{
print $key;
break;
}
An alternative to this approach is to call reset() and then key():
reset($pArray);
$first_key = key($pArray);
It's essentially the same as what is happening in the foreach(), but according to this answer there is a little less overhead.
Why not just do:
foreach($pArray as $k=>$v){
echo $k . ' - ' . $v . '<br>';
}
And you will be able to see the keys and their values at that point
array_keys function will return all the keys of an array.
To obtain the array keys:
$keys = array_keys($pArray);
To obtain the 1st key:
$key = $keys[0];
Reference : array_keys()
Related
I want to echo the most common number from an array. I have one array and I want to compare the previous key with the current key of my array. How do I do that?
I have made two foreach loops:
$mostCommon = 0;
foreach ($_SESSION['array'] as $key => $value) {
foreach ($_SESSION['array'] as $key2 => $value2){
$key++;
}
if(current key is higher than previous key){
$mostCommon = $value;
}
}
This is how I wan't to do it.
You can save the previous key outside the loop.
Example:
$previousKey = null;
foreach ($array as $key => $value) {
if ($key > $previousKey){ //If current key is greater than last key
}
$previousKey = $key;
}
$highestKey will be set to the biggest key in that array.
The most common number can be found using array_count_values.
The output of array_count_values is an associative array with key being the value, and value being the number of times it's in the array.
Sort the array with asort to preserve the keys.
Flip the array to get the value that is the most common and echo the last item.
$arr = [1,2,2,3,3,3,3,1,2,5,3,7];
$counts = array_count_values($arr);
asort($counts);
$flipped = array_flip($counts);
echo "most common number: " . end($flipped) . " is in the array " . end($counts) . " times";
//most common number: 3 is in the array 5 times
https://3v4l.org/qSD4J
I would like to combine these two foreach statements together. I've seen a few solutions around here, but nothing really works for me.
This is my username list from database.
$digits = [1,2,3,4];
$results = $db->table($usernames)
->where('memberID', $mID)->limit(10)
->getAll();
foreach ($results as $result) {
echo $result->userName;
}
I tried this:
$combined = array_merge($digits, $results);
foreach (array_unique($dogrularVeSiklar) as $single) : { ?>
{
echo $single.'<br>';
echo $results->userName;
},
}
You don't show what $dogrularVeSiklar is or where you get it, but as an example; combine into $key => $value pairs and foreach exposing the key and value:
$combined = array_combine($digits, $results);
foreach ($combined as $digit => $result) {
echo $digit . '<br>' . $result;
}
foreach operates on only one array at a time.
The way your array is structured, you can use array_combine() function to combine them into an array of key-value pairs then foreach that single array
I have two arrays namely arr and arr2.
var arr=[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}];
var arr2=[{"month":"January","ip":12},{"month":"June","ip":10}];
Is it possible to get array below shown from above two arrays?
result=[{"month":"January","url":1,"ip":12},{"month":"February","url":102},{"month":"March","url":192},{"month":"June","ip":10}];
If i use array_merge then i get answer as
result=[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192},{"month":"January","ip":12},{"month":"June","ip":10}];
You must decode JSON to arrays, manually merge them and again encode it to JSON :)
<?php
$arr = json_decode('[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]', true);
$arr2 = json_decode('[{"month":"January","ip":12},{"month":"June","ip":10}]', true);
$result = [];
foreach ($arr as &$item) {
if (empty($arr2))
break;
foreach ($arr2 as $key => $item2) {
if ($item['month'] === $item2['month']) {
$item = array_merge($item, $item2);
unset($arr2[$key]);
continue;
}
}
}
if (!empty($arr2))
$arr = array_merge($arr, $arr2);
echo json_encode($arr);
The first function that comes to mind is array_merge_recursive(), but even if you assign temporary associative keys to the subarrays, you end up with multiple January values in a new deep subarray.
But do not despair, there is another recursive function that can do this job. array_replace_recursive() will successfully merge these multidimensional arrays so long as temporary associative keys are assigned first.
Here is a one-liner that doesn't use foreach() loops or if statements:
Code: (Demo)
$arr=json_decode('[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]',true);
$arr2=json_decode('[{"month":"January","ip":12},{"month":"June","ip":10}]',true);
echo json_encode(array_values(array_replace_recursive(array_column($arr,NULL,'month'),array_column($arr2,NULL,'month'))));
Output:
[{"month":"January","url":1,"ip":12},{"month":"February","url":102},{"month":"March","url":192},{"month":"June","ip":10}]
The breakdown:
echo json_encode( // convert back to json
array_values( // remove the temp keys (reindex)
array_replace_recursive( // effectively merge/replace elements associatively
array_column($arr,NULL,'month'), // use month as temp keys for each subarray
array_column($arr2,NULL,'month') // use month as temp keys for each subarray
)
)
);
You should write your own function to do that
$res = [];
foreach ($arr as $item) {
$res[$item['month']] = $item;
}
foreach ($arr2 as $item) {
$res[$item['month']] = isset($res[$item['month']]) ? array_merge($res[$item['month']], $item) : $item;
}
var_dump($res);
I have following array of arrays:
$array = [
[A,a,1,i],
[B,b,2,ii],
[C,c,3,iii],
[D,d,4,iv],
[E,e,5,v]
];
From this one, I would like to create another array where the values are extract only if the value of third key of each subarray is, for example, greater than 3.
I thought in something like that:
if $array['2'] > 3){
$new_array[] = [$array['0'],$array['2'],$array['3']];
}
So in the end we would have following new array (note that first keys of the subarrays were eliminate in the new array):
$new_array = [
[D,4,iv],
[E,5,v]
];
In general, I think it should be made with foreach, but on account of my descripted problem I have no idea how I could do this. Here is what I've tried:
foreach($array as $value){
foreach($value as $k => $v){
if($k['2'] > 3){
$new_array[] = [$v['0'], $v['2'], $v['3']];
}
}
}
But probably there's a native function of PHP that can handle it, isn't there?
Many thanks for your help!!!
Suggest you to use array_map() & array_filter(). Example:
$array = [
['A','a',1,'i'],
['B','b',2,'ii'],
['C','c',3,'iii'],
['D','d',4,'iv'],
['E','e',5,'v']
];
$newArr = array_filter(array_map(function($v){
if($v[2] > 3) return [$v[0], $v[2], $v[3]];
}, $array));
print '<pre>';
print_r($newArr);
print '</pre>';
Reference:
array_map()
array_filter()
In the first foreach, $v is the array you want to test and copy.
You want to test $v[2] and check if it match your condition.
$new_array = [];
foreach($array as $v) {
if($v[2] > 3) {
$new_array[] = [$v[0], $v[2], $v[3]];
}
}
I'm wondering if the elements of array can 'know' where they are inside of an array and reference that:
Something like...
$foo = array(
'This is position ' . $this->position,
'This is position ' . $this->position,
'This is position ' . $this->position,
),
foreach($foo as $item) {
echo $item . '\n';
}
//Results:
// This is position 0
// This is position 1
// This is position 2
They can't "reference themselves" per se, and certainly not via a $this->position as array elements are not necessarily objects. However, you should be tracking their position as a side-effect of iterating through the array:
// Sequential numeric keys:
for ($i = 0; $i < count($array); ++$i) { ... }
// Non-numeric or non-sequential keys:
foreach (array_keys($array) as $key) { ... }
foreach ($array as $key => $value) { ... }
// Slow and memory-intensive way (don't do this)
foreach ($array as $item) {
$position = array_search($item, $array);
}
No, PHP's arrays are plain data structures (not objects), without this kind of functionality.
You could track where in the array you are by using each() and keeping track of the keys, but the structure itself can't do it.
As you can see here: http://php.net/manual/en/control-structures.foreach.php
You can do:
foreach($foo as $key => $value) {
echo $key . '\n';
}
So you can acces the key via $key in that example