Target array element that has a blank key/name - php

I have an array being generated by data which I have no control over and it returns the below array. Is there a way to target specifically the element that has a blank key/name?
I've tried $array[''], $array[' '] and $array[0] but none of them seem to work. Is there another way without looping through the array, the empty key/name can be anywhere in the array, it's not necessarily the last array element?
var_dump(array_keys($array)); gives me [0]=> string(2) " " for the element in question, I've tried targeting the element with a single and double space as the key/name but still gives an undefined index error.
I've also run serialize()on the keys from the array and the element with the blank key/name is returning s:2:" ";.
Array
Array
(
[desc] => Information etc.
[ref] => 2
[ ] => 123
)

It i probably not '' but something that shows up as '' (null maybe ?). Try var_dump(array_keys($array)) to get actual key values and types. this should show you the proper key to use

Related

How to get around PHP array forcing a key

I have a very simple array where I want to be able to add settings as simple as possible. In my case, if I don't need a second value, I don't need to add it.
Code
$settings = [
'my_string',
'my_array' => 'hello'
];
print_r($settings);
Result
The problem with my approach is that my_string is seen as a value and the key 0 is added.
Array
(
[0] => my_string
[my_array] => hello
)
I could check if the key is a number and in that case figure out that I don't use a second value.
Is there a better approach?
I'm aware of that I can use multiple nested arrays but then simplicity is gone.
The way you've written it, you wouldn't be able to access the value 'my_string' without some kind of key. There is always a key for any value, and if you don't specify values, PHP generates them as though they were indices in an actual array (PHP 'arrays' are actually dictionaries/maps/etc. that have default behavior in the absence of a specified key).
$settings = [
'name' => 'my_string',
'my_array' => 'hello'
];
If you don't want to use $settings[0] -- and I wouldn't want to either -- you should probably decide on a name for whatever 'my_string' is supposed to be and use that as its key.

Referencing part of an array and appending information to that index

Is it possible to add one array to the end of a specific index of another array?
I want to search each index for a specific value (in this case "apple").
Then I want to add a line of data after an index that has "apple" as its first value.
First array:
Array
(
[0] => apple,1,2,3
[1] => orange,a,b,c
)
Second array:
Array
(
[0] => apple,a,b,c
)
Final product:
Array
(
[0] => apple,1,2,3, apple,a,b,c
[1] => orange,a,b,c
)
Notice that I am ignoring the "orange" index because it did not match "apple".
I have tried "pushing" or "merging" the arrays but that does not seem to work.
Part of the problem is that I:
Do not know how to search an array for "Apple" if that word is part of a larger set of information within the array (e.g., apple, 1,2,3)
I do not know how to reference only part of an index (e.g., find part of the array that has "apple", and then add some information to that specific index).
Is this even possible to do? Excited to learn more about this!

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 }
}

Accessing specified Element of Array with Twig

I have the following array and i want to access the value of a specified element with twig.
numbers => Array ([01234567] => Array ( [0] => 9876543210 [1] => 8765432109 [2] => 0000000000))
I know there is only one entry in numbers, so I want to access the array with the key 01234567 directly.
Even tough numbers|keys[0] does return the correct key, I can't use it like numbers[numbers|keys[0]] to get the array. I also tried the attribute(array, item) function, but i didn't got it to work.
Is it possible to access it directly or do I need to use loops?
You have found a probably undocumented "feature" of Twig. If you check the source code, twig tries to determine if the given key is numeric, or not. It does this check with the ctype_digit function, which checks if a variable contains only numeric characters.
The example in your question contains an array key, which meets this conditions: it contains only numbers. Unfortunately, it also starts with a zero, which is removed when the string is converted into an integer.
I'm not exactly sure that this is intended behavior, so you may try to report this example as a bug.
For the current twig implementation, because everything except the loop construct uses the getAttribute function, you have no other choice but to use a for loop.

CakePHP returning double array from find('list) query

I'm using cakephp and am getting back a "double array" where it is giving me 2 arrays where it should be 1, I have looked into the issue as far as cakephp and can't figure it out and just want to move past this for now so I am wondering if anyone knows how to unset a second array if a variable has 2 arrays.. below is the print_r of the array, its just one variable that has this, which I find odd.. so I want to make it so there is not a 2nd set of duplicate values, if I do an array_push it pushes both values for that index into the resulting new array index so that won't work
one variable is equal to the following:
Array ( [0] => 42 [1] => 62 ) Array ( [0] => 42 [1] => 62 )
EDIT:
This is not an issue of my printing out the array twice accidentally, as I said above, with a foreach array_push of the variable, i end up with this, which is odd:
Array ( [0] => 4242 [1] => 6262 )
EDIT:
This is the cakephp database call that I am using, I know I didn't ask this in regards to cakephp but since some people think this is impossible i am posting this just so you can see what it does if you want
$specificfields_array = $this->Mymodel->find('list', array('fields' =>'Mymodel.id'),
'conditions' => array('emailgroup' => $categorynumber, 'sent' => '0');));
EDIT:
This is what a "foreach" array_push is:
$mynewarray = array();
foreach ($specificfields as $specificfields_current) {
array_push ($mynewarray, $specificfields_current);
}
A variable cannot "have two arrays". It can be one array that has two arrays nested. The scenario you describe is impossible (probably there are two print_r there or there is a < character hiding stuff – check the HTML source).
Can you post the controller, the model and the view file with your print_r calls to the http://bin.cakephp.org/ site and post the links back here so we can see all of your code?

Categories