Codeigniter, array in session, change the value of array in session in a specific key - php

I have a variable in session that contains array of numbers. I want to change a specific number inside that variable.
My session:
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => true,
// 20 slots, the counting starts from 0, the last slot's position
// is 19.
'slots_id' => array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
);
So, slots_id is the variable that i want to access. I need to change the last number, it.In my controller i have the following.
$this->session->set_userdata('slots_id'[19], 100);
Here i'm trying to set the last slot's value to 100. But the "[19]" that i put there causes error.
A PHP Error was encountered Severity: Notice Message: Uninitialized string offset: 19
Google did not help me in my current situation, thank you for your time.

Two ways around your problem:
$this->session->set_userdata('slots_id'[19], 100); is not attempting to assign a value of 100 to the array element on index 19 for the $slots_id array. It's trying to set a value of 100 as the 20th character (index 19) of the 'slots_id' string, which goes out of bounds.
You may try:
$this->session->set_userdata('slots_id[19]', 100);
Or even better, remove the full element from session, update it and reset it:
$aux = $this->session->userdata('slots_id');
$aux[19] = 100;
$this->session->unset_userdata('slots_id');
$this->session->set_userdata('slots_id', $aux);
it's a bit more code, but my advice would be to always replace session data rather than update it on the fly.

Uninitialized string offset errors in PHP have a vast amount of documentation around them. You are getting this error because you are not referencing index 19 of an Array, you're referencing it of a string, which is exactly what 'slots_id' is in this instance. 'slots_id' is 8 characters long which means any index beyond 7 is in fact undefined.
If you have no direct access to the $_SESSION superglobal for some odd reason, you need to retrieve the entire slots_id array via the helper, update the index you need in your local copy, then update the session variable's slots_id array with your updated copy.

Related

Notice: Trying to access array offset on value of type int in. how to fix it?

How to fix it?
Notice: Trying to access array offset on value of type int in
C:\xampp\htdocs\SPP2\petugas\admin\kelas\id_kelas.php on line
12
This is the code:
$nilaikode = substr($jumlah_data[0], 1);
As others in the comments have noted, the value of $jumlah_data in this case is an integer, but it's being used as an array.
You'll likely want to trace back to where $jumlah_data is set and use something like var_dump($jumlah_data) to see what the value is and determine if it's what you expect.
Then either fix the way the variable is set so it is an array, or modify your code so that it treats the value as an integer - e.g.
$nilaikode = substr($jumlah_data, 1);

Undefined offset in array - But I know it's in there

I have an array (or associative array), with keys and values.
Then, when trying to read one of the keys, which IS in the array, I get an "undefined offset" notice.
I have two examples where it happened. One was "exploding" a string like "AAA|BBB|CCC", using | as the separator, then trying to read the resulting array at position 1.
var_dump() correctly shows an array having offsets 0 to 2, with the correct values. But I still get the notice.
Another example is I get an array (from an AJAX call, I json_decode it, etc), then I typed the following code:
foreach (array_keys($myDecodedArray) as $k) {
$value = $myDecodedArray[$k];
someOtherCode();
}
I had that damn notice appear when trying to read $myDecodedArray[$k], although php itself had just told me the key existed !
So, I solved that last case by going
foreach ($myDecodedArray as $k => $value) {
someOtherCode();
}
but still, this is extremely annoying, and makes no sense to me.
Any of you run into that problem before?
Do you have any information about what could cause that?
[EDIT]
Rahul Meshram's suggestion (which I upvoted in the comments) solved my second problem case.
However, the first case still happens (exploding a string into an array, then trying to access that array's values by their numeric keys).
The keys ARE numeric (gettype returns 'integer', var_dump on that key shows an integer too, with the right value), but trying to access $explodedArray[1] still results in that notice being displayed, despite $explodedArray having keys 0, 1, and 2, with associated values.

Undefined offset while printing multidimensional array in PHP

I have a multidimensional array in PHP which looks like this
$names_of_tragedies=array(
$row["Character_code"]=>array(
($another_counter)=>$temp_string)
)
I am creating an array called $names_of_tragedies.
It has several subsets or sub-arrays, with each sub-array being named $row["Character_code"] and the "Character_Code" is different for each sub-array.
Each of these sub-arrays has another array within, with the header field being called $another_counter. $another_counter is a numerical value, so it ranges from 1 to a fixed number.
I am entering the data correctly. I have checked it. The problem is with printing it.
Whereas I can access every sub-array $row["Character_code"], I can access only the final sub-sub-array $another_counter.
For e.g., if I have a sub-array where $row["Character_code"]='Prometheus' and 'Prometheus' has only one sub-sub-array [1] whose value is 'APB', I can print it, using
echo $names_of_tragedies[$row["Character_code"]][$another_counter];
The problem occurs when a sub-sub-array has multiple values.
For e.g., if I have a sub-array where $row["Character_code"]='Antigone' and 'Antigone' has 5 sub-sub-arrays [1],[2],[3],[4] and [5] whose value is
[1]='ASAT',[2]='SANTIGONE',[3]='SOTK',[4]='SOAC' and [5]='EPW',
then creating a loop where the value of the variable $another_counter changes from 1 to 5, and using $row["Character_code"]='Antigone,
echo $names_of_tragedies[$row["Character_code"]][$another_counter];
only successfully returns the value of EPW. For every other occasion when $another_counter=1,2,3 or 4,
it says
Undefined offset: 1 or Undefined offset: 2 or Undefined offset: 3 or
Undefined offset: 4
. It is only when I reach the final value, 5, that it displays the data, 'EPW'.
Somehow the counter seems to be set to the last or only value. How do I print the earlier sub-sub-arrays?
The code you have shown where you fill this array, seems to overwrite the array under the key $row["Character_code"] every single time, instead of actually adding items to it.
Those four initial lines should probably rather be something like this:
$names_of_tragedies[$row["Character_code"]][$another_counter] = $temp_string;
That will add all the $temp_strings to the array that is $names_of_tragedies[$row["Character_code"]], using $another_counter as the key for each item.

PHP array of unknown length with 0 as initial value

I have PHP $_SESSION arrays that have an undefined amount of elements. Is it possible to initialise all the values to 0, or do I have to check whether the value is NULL and then set to 0 every time I check a value?
Edit: I'm sorry for the vagueness of my question.
I have an undefined amount of levels, and I'd like to store all the scores of each level in that array. Currently my amount of levels is fixed, so I am currently just writing:
$_SESSION['totals'] = array(0,0,0,0,0);
And then when adding manipulating the data, I simply increment/add a certain amount to that element.
Now I'd prefer to have the same ease of directly incrementing/adding values to certain elements without needing to check whether a value is NULL or something like that...
Edit 2: edited my code as follows:
$_SESSION['totals'] = array();
if(array_key_exists($row['level']-1,$_SESSION['totals'])){
$_SESSION['totals'][$row['level']-1]++;
}else{
$_SESSION['totals'][$row['level']-1] = 1;
}
And it seems to work. Thanks fellas!
You can use array_fill_keys function to fill an array with specified value for defined keys:
$keys = array('foo', 'bar', 'baz');
$output = array_fill_keys($keys, 0);
Defining an array with initial values is defining an array with a length. This does not prevent you from adding or removing elements from the array:
// initial array
$myArray = [0, 0, 0, 0];
print_r($myArray); // would output Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0)
$myArray[] = 1;
print_r($myArray); // would output Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 1 )
$_SESSION contains only what you put into it. Just make sure you add 0 instead of null the first time you add something.
If you need to do this later, I think your design might be bad. But anyway, $_SESSION is like a normal array, so you can just use PHP's array function to traverse the array and check or change each value.
PHP arrays aren't really arrays you might know from other languages. They really are more like linked lists with hash access.
What this means is: You either know all the string array indices you want to use, and either make sure they exist, or you check their existence every time you access them which might fail.
For numeric indices, the same thing applies. You might have an array with indices 1, 2 and 4 present, but if you run over it with only a for loop, you will trigger a notice when accessing the nonexistant element 3.
Use foreach loops whenever you want to iterate arrays. Check with isset() whenever you want to document that the array value might not be present. Don't do it if you know or assume that the array element MUST be present - if not, you get the notice as a reminder that your code is working on a data structure that is NOT what you thought it is. Which actually is a good thing. Then fix it. :)
Your best bet would be to abstract your session stuff by creating facade methods, or getters and setters around the session variables rather than access them directly. This way you can return a default value if the one you're after doesn't exist.
I've used array_key_exists() to check if the index is set. If it is not, I display 0 or add store a certain value in that field, else I show the value of that index or add certain value to that field.
Credit to Sven for bringing that up.
to check what u have in your sessions, loop tru it. not sure if this is what u are asking.
foreach($_SESSION as $x=>$y)
{
if(empty($x)) { //do something }
}

Session variables seem not to be saved

Quite simple code:
<?
session_start();
$_SESSION['t'.time()] = "ok";
echo "<pre>".print_r($_SESSION, 1)."</pre>";
?>
shows, as expected, something like
Array
(
[t1330966834] => ok
[t1330966835] => ok
[t1330966836] => ok
)
after 3page reloads.
Let's change a few symbols:
$_SESSION[time()] = "ok";
(now without 't') and I expect after few reloads something like
Array
(
[t1330966834] => ok
[t1330966835] => ok
[t1330966836] => ok
[1330967020] => ok
[1330967021] => ok
[1330967022] => ok
[1330967023] => ok
)
But actually the result is absolutely different:
Array
(
[t1330966834] => ok
[t1330966835] => ok
[t1330966836] => ok
[1330967020] => ok
)
We have 3 previous array cells ad one and only one 'time' cell - no matter how many times you reload the page. The time is correct, it different each second but only one cell without 't'!
Also I tried
$t =time();
$_SESSION[$t] = "ok";
and even
$t =intval(time());
$_SESSION[$t] = "ok";
But it's remains only one cell with time.
Tested at php 5.2.13 and 5.3.10 at 2 different servers.
What am I doing wrong?
The keys in the $_SESSION associative array are subject to the same limitations as regular variable names in PHP, i.e. they cannot start with a number and must start with a letter or underscore. For more details see the section on variables in this manual.
http://php.net/manual/en/session.examples.basic.php
When cranking error_reporting way up, you should notice this:
Notice in <file>, line ...: session_write_close(): Skipping numeric key 1330967020
Numeric indeces to session variables are not supported.
This is not a strange thing. It is simply skipping numeric keys. You can see this error, if you have enabled the notice to be displayed.
As mentioned on this comment on php.net. You should not use numeric keys to define values in session.
Quote
Careful not to try to use integer as a key to the $_SESSION array (such as $_SESSION[0] = 1;) or you will get the error "Notice: Unknown: Skipping numeric key 0. in Unknown on line 0"

Categories