I've seen questions like this, but if I assign a key-value pair to an empty array lik this
$arr[$key] = $value;
I get the php notice
Notice: Undefined index: <key> in <path>
where of course <key> is whatever value was in $key.
How can I assign a value to a new key, without triggering a Notice?
Thanks!
edit: heres your more precise code. This is exactly whats in my code. Does this any difference?
while( list( $k, $sum ) = mysql_fetch_row( $res ) ) {
if( $sum < 0 ) {
$churn[$k] += $sum;
}
}
declare your array before addind the key
$arr = array();
$arr[$key] = $value;
or simply do
$arr = array($key=>$value);
what do you mean [$value]
You're trying to get the value of a brand new array with a given key
Your syntax isnt correct. Just try my quick testcase which wont throw any notice.
<?php
error_reporting(E_ALL);
$array = array();
$key = 'new_key';
$value = 'new_value';
$array[$key] = $value;
echo '<pre>';
var_dump($array);
exit;
?>
The problem layed in
while( list( $k, $sum ) = mysql_fetch_row( $res ) ) {
if( $sum < 0 ) {
$churn[$k] += $sum;
}
}
due to the += operator. The first time, it gets called, churn['whateverWasIn$k'] is not set. The second time is fine though.. So to get rid of the notices, it has to be like:
(!isset($churn[$k])) ? $churn[$k] = $sum : $churn[$k] += $sum;
Realize the missing + in the middle statement. So if this key does not exist by the time, i want to increase it by $sum, declare it and give it the value of $sum, otherwise just add $sum to the current value.
That's all. It doesn't look to pretty in code, but it gets me rid of 200 notices. Which also doesn't look too nice in my view.
Thanks for your help.
Related
I can not figure out how to print all $_POST array items (ending in successive numbers) if one or more numbers do not exist. Not sure how to explain this... For example..
$i = 1;
while( isset($options['item_code'.$i]) )
{
echo $options['item_code'.$i];
$i++;
}
This code works fine as long as the numbers continue to exist in order...
item_code, item_code1, item_code2, item_code3, etc...
But once a number is removed, the if statement stops and the rest of the values are not printed. For example...
item_code, item_code1, item_code3, etc...
Will stop at "item_code1" because item_code2 does not exist.
I've tried solutions given to similar questions here on stackoverflow but they either do not work, do the same thing, or create a continuous loop.
I would appreciate any help that someone can give me here.
you are doing it in wrong way. Please update your code like this. replace $i<=4 with number of element you want to trace
$key = end(array_keys($options));
$dataa = explode('item_code',$key);
$count = $dataa[1];
$i = 1;
while( $i <= $count )
{
if(isset($options['item_code'.$i])){
echo $options['item_code'.$i];
}
$i++;
}
I guess it can be done with an array_filter and strpos functions:
<?php
$codes = array_filter($options, function ($key) {
return strpos($key, 'item_code') === 0;
}, ARRAY_FILTER_USE_KEY);
foreach ($codes as $code) {
echo $code . PHP_EOL;
}
Instead of while use foreach like
foreach($options as $option){
echo $value;
}
Given this code (https://psalm.dev/r/156e52eb66):
<?php
function keys(): array
{
return ['foo', 'bar'];
}
// no lines above can be changed
foreach (keys() as $k) {
echo gettype($k);
}
how would one type it assuming the keys function is not under our control (in a different project) and it effectively returns an array of mixed (array<array-key, mixed>).
So, one may only change the loop and around it.
Is it even possible?
UPD: I reported https://github.com/vimeo/psalm/issues/2025
If I get it right this might help you:
foreach (array_keys(keys()) as $k) {
echo gettype(keys()[$k])."\n";
}
You could use for loop instead of foreach loop to fix the warning.
$keys = keys();
for( $i = 0; $i < count( $keys); $i++ ) {
echo gettype( $keys[$i] );
}
Here is the link in Psalm https://psalm.dev/r/20c1cbab73
It's a bug of psalm.
Refer to Github: INFO: MixedAssignment - Cannot assign to a mixed type | when using string array key #1281,
And it has been fixed by muglug in this commit 6033345694727d7c3cf84adc76507c3785ed0295
i have an array of undefined size, for example :
<?php
$array["foo"] = 86 ;
$array["bar"] = 49 ;
$array["matt"] = 96 ;
?>
i don't want to disturb array's internal pointer , but want to get a COPY of second last value of array instead.
I don't know, why you use a map, when in fact you want an ordered list instead, but
$tmp = array_values($array);
echo $tmp[count($tmp) -2];
should do it. With php5.4 this should work either
echo array_values($array)[count($array)-2];
I'm not sure what size your array is planned for, so copying all values into a separate array might not be a good idea.
The following code slices out an array of length 1 just from the second last position and sets $key and $value.
$pair = array_slice($array, -2, 1, true);
$key = key($pair);
$value = current($pair);
PS: Should probably be put into a simple separated function?!
You can do it this way.
$array["foo"] = 86 ;
$array["bar"] = 49 ;
$array["matt"] = 96 ;
$x = count($array);
foreach($array as $row)
{
if($x == 2)
{ $secondLast = $row;}
$x--;
}
echo $secondLast;
Because you are using associative array.
I have an array that looks like this:
Array([5258]=>5274,
[5261]=>5281,
[5264]=>5287,
[5271]=>5289 );
I want to modify this array so that any overlaps in key value pairs are removed.
To elaborate, the first key value pair should become [5258]=>5289, because the numerical value of the each of the rest of the keys is less than 5274, the original value corresponding to the first key.
What would be the best way to do this using PHP? I'll appreciate some pointers on this.
Thanks.
EDIT: Just a reword to the background for my question:
If there's an array like this:
Array([10]=>12
[11]=>15
[16]=>20)
I want to derive another array/modify the same array to get
Array([10]=>15
[16]=>20)
I hope this makes things clearer.
Is this a game of guess the actual question?
This is my answer to what I think the question is:
$arr = Array(
5258=>5274,
5261=>5281,
5264=>5287,
1=>100,
50=>70,
40=>130,
5271=>5289
);
ksort($arr);
$out = array();
$start = null;
foreach ( $arr as $from=>$to )
{
if ( $start === null )
{
$start = $from;
$end = $to;
} else {
if ( $from < $end )
{
$end = max($end,$to);
} else {
$out[$start] = $end;
$start = null;
}
}
}
if ( $start !== null ) $out[$start] = $end;
print_r($out);
output:
Array
(
[1] => 130
[5261] => 5289
)
<?php
$arr = array(5258=>5274,
5261=>5281,
5264=>5287,
5271=>5289 ,
5301=>5400);
ksort($arr);
$new = array();
$currentkey = reset(array_keys($arr));
$currentvalue = reset($arr);
foreach($arr as $key=>$value){
if($key > $currentvalue){
$new[$currentkey] = $currentvalue;
$currentkey = $key;
}
$currentvalue = max($currentvalue,$value);
}
$new[$currentkey] = $currentvalue;
var_dump($new);
?>
Take a look at usort() but I'm not quite sure how it works. It's a bit black magic for me. At a guess, make a function which compares the key values and orders the array like that.
Or you could tinker with array_merge()
Apologies for a waffling answer, I don't quite understand your question, or the criteria for how you want to merge/sort your array
$arr[] = $new_item;
Is it possible to get the newly pushed item programmatically?
Note that it's not necessary count($arr)-1:
$arr[1]=2;
$arr[] = $new_item;
In the above case,it's 2
end() do the job , to return the value ,
if its help to you ,
you can use key() after to petch the key.
after i wrote the answer , i see function in this link :
http://www.php.net/manual/en/function.end.php
function endKey($array){
end($array);
return key($array);
}
max(array_keys($array)) should do the trick
The safest way of doing it is:
$newKey = array_push($array, $newItem) - 1;
You can try:
max(array_keys($array,$new_item))
array_keys($array,$new_item) will return all the keys associated with value $new_item, as an array.
Of all these keys we are interested in the one that got added last and will have the max value.
You could use a variable to keep track of the number of items in an array:
$i = 0;
$foo = array();
$foo[++$i] = "hello";
$foo[++$i] = "world";
echo "Elements in array: $i" . PHP_EOL;
echo var_dump($foo);
if it's newly created, you should probably keep a reference to the element. :)
You could use array_reverse, like this:
$arr[] = $new_item;
...
$temp = array_reverse($arr);
$new_item = $temp[0];
Or you could do this:
$arr[] = $new_item;
...
$new_item = array_pop($arr);
$arr[] = $new_item;
If you are using the array as a stack, which it seems like you are, you should avoid mixing in associative keys. This includes setting $arr[$n] where $n > count($arr). Stick to using array_* functions for manipulation, and if you must use indexes only do so if 0 < $n < count($arr). That way, indexes should stay ordered and sequential, and then you can rely on $arr[count($arr)-1] to be correct (if it's not, you have a logic error).