Function use and omitting arguments - array_slice - php

Hi I want to get all the elements of an array after a particular point AND maintain the keys.
How do I pass array_slice a null value for the third argument so that I can pass true for the fourth argument? I tried 'null'.
array_splice($array_name,3,null,true)
And/or is there a better way to do this?
Edit: To complete this question: Is there a way to pass a null value for the 3rd parameter. It seems like this is a weakness in this function if you can't pass a null value or 'placeholder'

Just pass the length of the array:
array_slice($array_name, 3, count($array_name)-3, true);

If you dont expect evil big array, you can set PHP_INT_MAX
array_slice($array_name, 3, PHP_INT_MAX, true);

Related

Declaring an optional array argument

I was wondering if there is any difference when setting default array value to be an empty array or NULL.
For example:
function arrayTest(array $array = array()) {
if(!empty($array)) {
// Do something
}
}
or
function arrayTest(array $array = NULL) {
if(!empty($array)) {
// Do something
}
}
What I noticed is that first example doesn't allow NULL values to be passed and the second example does because of type casting.
Any other differences? Which one should be used?
The other difference is that if you don't pass an argument , it will default to array() or null, which are two very distinct values. You can check for that of course, but you will need to take it into account. empty will work for both, but a foreach loop over null won't work that well, and various array functions will also fail.
What you noticed is correct: Passing null for a typehinted argument only works if you add = null to the declaration. This is not only true for arrays but for objects as well. In PHP there is no way in PHP to make a typehinted argument that is mandatory but can be null. As soon as you add =null to the declaration, you can pass null but you can also omit the parameter.
If to you there is no logical difference between an empty array or null, I would choose the first method of defaulting to an empty array. Then at least you'll know that the input is always an array. I think that add clarity to both the implementer of the function and the programmer(s) who use it. But I guess that's just an opinion and not even a strong one.
My main advice would be to not make the argument optional at all. In my experience this will make the usage of such functions unclear, especially as the code grows and more arguments are added.

delete null values from an array in php

I have an array in php $arr("ABC","","XYZ","",""). now i want to trim the null values in the array and want $arr("ABC","XYZ"). And the element number must also be manipulated likewise which means "XYZ" must have the key value as 1 after trimming. How do we do it? Thanks in advance! Cheers!
Use array_filter()
Filters elements of an array using a callback function. If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed.
$arr = array_filter($arr);

How to check an associative array for all null values in php?

This is probably a very trivial question, but please bear with me.
I am trying to read a lot of data into an array of associative arrays. The data contains a lot of empty arrays and arrays with keys set and but all null values. I want to ignore those and only push arrays with at least one key mapped to a non-null value. (The data comes from an excel sheet and it has lots of empty cells that are registered as "set" anyway.) So far I have tried:
if(!empty(${$small_dummy}))
array_push(${$big_dummy}, ${$small_dummy});
That gets rid of the empty arrays but not the ones where all keys map to null. Is there a better way to do this than looping through the entire array and popping all null values?
Judging by the code you have already, you can change:
if(!empty(${$small_dummy}))
to:
if(!empty(array_filter(${$small_dummy})))
That will filter out all empty values (values evaluating to FALSE to be precise) and check if the resulting array is empty. Also see the manual on array_filter().
Note that this would also filter 0 values so you might need to write a custom callback function for array_filter().
You can try if(!array_filter($array)) { also
This isn't an ideal approach, but array_sum will return 0 if all values can't be cast to a numeric value. So :
$small_dummy = array("a" => null, "foo", "", 0);
if(array_sum($small_dummy) === 0)
would pass. But this is only the way to go if you are expecting the values to be numeric.
Actually, if the problem is that the array keys have values and therefor are not passing as empty(), the go with array_values:
if(!empty(array_values(${$small_dummy})))

PHP associative arrays keys only

Is it possible to declare an array element key and not define it a value (like non-array variables)? This way if you have an associative array of booleans, you need only check if the key exists rather than assigning a boolean value. But you'd still have the advantage of not having to iterate over the array when checking if a key exists.
This would be a space saving measure. It appears 'null' gets allocated space.
No. Array element always have key and value, however you may just put anything as your value if you do not care (i.e. empty string). In your case you should just add these keys to your array which are of value i.e. true. And then when you will be looking for it and will be unable to find you can assume it's false. But in general you are doing things wrong. You are NOT really saving here but make your code unclean and hard to read and maintain. Do not do this
If you don't want to have a dictionary structure like in an accoc array, then you just want a set of values, like this:
$array = ('red', 'green', 'blue');
To check if a key (item) exists just use in_array():
if(in_array('red', $array)) {
// -> found
}
However,you should note that php will internally create numeric indicies in this case.
Another way to go would be to assign TRUE to all values. This would at least take less memory. Like this
$array (
'red' => TRUE,
'green' => TRUE,
'blue' => TRUE
);
and check existence using isset() Like:
if(isset($array['red'])) {
// -> found
}
Note: I wouldn't advice you to use NULL as the value. This because you cannot use isset() in this case as isset will return false if the value of a key is NULL. You'll have to use array_key_exists() in this case what is significantly slower than isset().
Conclusion: In terms of processor and memory consumption I would suggest the second advice in PHP. The memory consumption should be the same as with numeric arrays but search operations are optimized.
If i understand correctly.
You plan to use an associative array like this:
key value
"bool1" ""
"bool2" ""
"bool3" ""
And if a key exists, then the bool is "true".
Why not just use an ordinary array like this?:
key value
1 "bool1"
2 "bool2"
3 "bool3"
If the value exists, then the bool is "true".
Yes it's possible. You can also use array_key_exists to check for those values. PHP seperates the hash map of variable names from the actual storage of data (google on zval if you're interested). With that said, arrays pay an additional penalty in having to also have an associated "bucket" structure for each element, that depending on your os and compile options can be as large as 96 bytes/per. Zvals are also as much as 48 bytes each, btw.
I don't think there's any chance you're going to get much value from this scheme however, but purely from a hypothetical standpoint, you can store a null value.
<?php
$foo = array('a' => null, 'b' => null);
if (array_key_exists('a', $foo))
echo 'a';
This does not save you any memory however, if compared to initializing to a boolean. Which would then let you do an isset which is faster than making the function call to array_key_exists.
<?php
$foo = array('a' => true, 'b' => true);
if (isset($foo['a']))
echo 'a';

How to check if an array has an element at the specified index?

I know there is array_key_exists() but after reading the documentation I'm not really sure if it fits for this case:
I have an $array and an $index. Now I want to access the $array, but don't know if it has an index matching $index. I'm not talking about an associative array, but an plain boring normal numerically indexed array.
Is there an safe way to figure out if I would really access an $array element with the given $index (which is an integer!)?
PHP may not care if I access an array with an index out of bounds and maybe just returns NULL or so, but I don't want to even attempt to code dirty, so I want to check if the array has the key, or not ;-)
You can use either the language construct isset, or the function array_key_exists : numeric or string key doesn't matter : it's still an associative array, for PHP.
isset should be a bit faster (as it's not a function), but will return false if the element exists and has the value NULL.
For example, considering this array :
$a = array(
123 => 'glop',
456 => null,
);
And those three tests, relying on isset :
var_dump(isset($a[123]));
var_dump(isset($a[456]));
var_dump(isset($a[789]));
You'll get this kind of output :
boolean true
boolean false
boolean false
Because :
in the first case, the element exists, and is not null
in the second, the element exists, but is null
and, in the third, the element doesn't exist
On the other hand, using array_key_exists like in this portion of code :
var_dump(array_key_exists(123, $a));
var_dump(array_key_exists(456, $a));
var_dump(array_key_exists(789, $a));
You'll get this output :
boolean true
boolean true
boolean false
Because :
in the two first cases, the element exists -- even if it's null in the second case
and, in the third, it doesn't exist.
You can easily use isset():
if (isset($array[$index])) {
// array index $index exists
}
And as you have suggested, PHP is not very kind if you try to access a non-existent index, so it is crucial that you check that you are within bounds when dealing with accessing specific array indexes.
If you decide to use array_key_exists(), please note that there is a subtle difference:
isset() does not return TRUE for array
keys that correspond to a NULL value,
while array_key_exists() does.
That's exactly what the array_key_exists is for. It works on both numerical and string indexes.

Categories