PHP Get all numerical/anonymous keys in an array - php

I have a multidimensional array, I am interested in getting all the elements (one level deep) that don't have named keys.
i.e.
Array
{
['settings'] {...}
['something'] {...}
[0] {...} // I want this one
['something_else'] {...}
[1] {...} // And this one
}
Any ideas? Thanks for your help.

This is one way
foreach (array_keys($array) as $key) {
if(is_int($key)) {
//do something
}
}
EDIT
Depending on the size of your array it may be faster and more memory efficient to do this instead. It does however require that the keys are in order and none are missing.
for($i=0;isset($array[$i]);$i++){
//do something
}

$result = array();
foreach ($initial_array as $key => $value)
if ( ! is_string( $key ) )
$result[ $key ] = $value;

The key is 0, Shouldn't be $your_array[0]?

Related

How to get every key-value-pair from PHP-array

I need to get every key-value-pair from an array in PHP. The structure is different and not plannable, for example it is possible that a key contains an additional array and so on (multidimensional array?). The function I would like to call has the task to replace a specific string from the value. The problem is that the function foreach, each, ... only use the main keys and values.
Is there existing a function that has the foreach-function with every key/value?
There is not a built in function that works as you expect but you can adapt it using the RecursiveIteratorIterator, walking recursively the multidimensional array, and with the flag RecursiveIteratorIterator::SELF_FIRST, you would get all the elements of the same level first, before going deeper, not missing any pair.
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $key => $item) {
// LOGIC
}
The usual approach to this kind of task is using a recursive funcion.
Let's go step by step:
First you need the foreach control statement...
http://php.net/manual/en/control-structures.foreach.php
..that let you parse the associative array without knowing keys' names beforehand.
Then is_array and is_string (and eventually is_object, is_integer...) let you check the type of each value so you can act properly.
http://php.net/manual/en/function.is-array.php
http://php.net/manual/en/function.is-string.php
If you find the string to be operated then you do the replace task
If you find an array the function recalls itself passing the array just parsed.
This way the original array will be parsed down to the deepest level without missing and key-value pair.
Example:
function findAndReplaceStringInArray( $theArray )
{
foreach ( $theArray as $key => $value)
{
if( is_string( $theArray[ $key ] )
{
// the value is a string
// do your job...
// Example:
// Replace 'John' with 'Mike' if the `key` is 'name'
if( $key == 'name' && $theArray[ $key ] == "John" )
{
$theArray[ $key ] = "Mike";
}
}
else if( is_array( $theArray[ $key ] )
{
// treat the value as a nested array
$nestedArray = $theArray[ $key ];
findAndReplaceStringInArray( $nestedArray );
}
}
}
You can create a recursive function to treat it.
function sweep_array(array $array)
{
foreach($array as $key => $value){
if(is_array($value))
{
sweep_array($value);
}
else
{
echo $key . " => " . $value . "<br>";
}
}
}

How can I rename some keys in a PHP array using another associative array?

Given a data array ...
$data_array = array (
"old_name_of_item" => "Item One!"
);
... and a rename array ...
$rename_array = array (
"old_name_of_item" => "new_name_of_item"
);
... I would like to produce an output like this:
Array
(
[new_name_of_item] => Item One!
)
I have written the following function, and while it works fine, I feel like I'm missing some features of PHP.
function rename_keys($array, $rename_array) {
foreach( $array as $original_key => $value) {
foreach( $rename_array as $key => $replace ) {
if ($original_key == $key) {
$array[$replace] = $value;
unset($array[$original_key]);
}
}
}
return $array;
}
Does PHP offer built-in functions to help with this common problem? Thanks!
You only have to go through the array once:
function rename_keys($array, $rename_array) {
foreach ( $rename_array as $original_key => $value ) {
if (isset($array[$original_key])) {
$array[$rename_array[$original_key]] = $array[$original_key];
unset($array[$original_key]);
}
}
}
This assumes, of course, that both arrays are correctly filled (unique values for the replacement keys).
Edit: only replace if a corresponding element exists in $rename_array.
Edit 2: only goes through $rename_array
Second time today. This one is easier:
$data_array = array_combine(
str_replace(array_keys($rename_array), $rename_array, array_keys($data_array)), $data_array);

foreach and multidimensional array

I have a multidimensional array and I want to create new variables for each array after apllying a function. I dont really know how to use the foreach with this kind of array. Here's my code so far:
$main_array = array
(
[first_array] => array
(
['first_array1'] => product1
['first_arrayN'] => productN
)
[nth_array] => Array
(
[nth_array1] => date1
[nth_arrayN] => dateN
)
)
function getresult($something){
## some code
};
foreach ($main_array as ["{$X_array}"]["{$key}"] => $value) {
$result["{$X_array}"]["{$key}"] = getresult($value);
echo $result["{$X_array}"]["{$key}"];
};
Any help would be appreciated!
foreach ($main_array as &$inner_array) {
foreach ($inner_array as &$value) {
$value = getresult($value);
echo $value;
}
}
unset($inner_array, $value);
Note the &, which makes the variable a reference and makes modifications reflect in the original array.
Note: The unset is recommended, since the references to the last values will stay around after the loops and may cause unexpected behavior if you're reusing the variables.
foreach($main_array AS $key=>$array){
foreach($array AS $newKey=>$val){
$array[$newKey] = getResult($val);
}
$main_array[$key] = $array;
}

Adding key=>value pair to existing array with condition

Im trying to add a key=>value to a existing array with a specific value.
Im basically looping through a associative array and i want to add a key=>value foreach array that has a specific id:
ex:
[0] => Array
(
[id] => 1
[blah] => value2
)
[1] => Array
(
[id] => 1
[blah] => value2
)
I want to do it so that while
foreach ($array as $arr) {
while $arr['id']==$some_id {
$array['new_key'] .=$some value
then do a array_push
}
}
so $some_value is going to be associated with the specific id.
The while loop doesn't make sense since keys are unique in an associative array. Also, are you sure you want to modify the array while you are looping through it? That may cause problems. Try this:
$tmp = new array();
foreach ($array as $arr) {
if($array['id']==$some_id) {
$tmp['new_key'] = $some_value;
}
}
array_merge($array,$tmp);
A more efficient way is this:
if(in_array($some_id,$array){
$array['new_key'] = $some_value;
}
or if its a key in the array you want to match and not the value...
if(array_key_exists($some_id,$array){
$array['new_key'] = $some_value;
}
When you use:
foreach($array as $arr){
...
}
... the $arr variable is a local copy that is only scoped to that foreach. Anything you add to it will not affect the $array variable. However, if you call $arr by reference:
foreach($array as &$arr){ // notice the &
...
}
... now if you add a new key to that array it will affect the $array through which you are looping.
I hope I understood your question correctly.
If i understood you correctly, this will be the solution:
foreach ($array as $arr) {
if ($arr['id'] == $some_id) {
$arr[] = $some value;
// or: $arr['key'] but when 'key' already exists it will be overwritten
}
}

How do I remove the nulls out of the inner PHP array

I have an array from which I need to remove null values:
[227] => Array
(
[0] => 3
[1] => 8
[2] =>
[3] =>
[4] => 1
)
)
I tried array_filter($quantity);
and also
foreach ($quantity as $key => $value) {
if (is_null($value) || $value=="") {
unset($quantity);
}
}
and even tried the foreach with $quantity[0] and got Undefined offset 0. Any ideas?
UPDATE
This works but what if i dont have the 227
foreach ($quantityval[227] as $key => $value) {
if (is_null($value) || trim($value)=="") {
unset($quantityval[227][$key]);
}
}
This looks like a nested array -- your foreach statement looks correct, but needs to check the inner arrays:
foreach ($quantity as $key => $item)
foreach ($item as $key2 => $item2) {
if (is_null($item2) || $item2=="") {
unset($quantity[$key][$key2]);
}
}
}
You appear to have values that are all white-space -- either regular spaces or possibly unicode characters. Try trim($value) == "".
If that doesn't work array_filter($array, "is_integer"); may do the trick.
You updated solution works. The part about the hardcoded 227 is because $quantity is a multi-dimensional array (the extra closing parenthesis hinted that too). You need to do nested foreach for that.
foreach($bigArray as $bigKey => $smallArray)
{
foreach($smallArray as $smallKey => $value)
{
if(is_null($value) || $value == "")
unset($bigArray[$bigKey][$smallKey]);
}
}
I use something like this for situations like that:
<?php
function filter_empty_recursive($arr)
{
$keys = array_keys($arr);
foreach($keys as $key)
{
if(is_array($arr[$key]))
{
$arr[$key] = filter_empty_recursive($arr[$key]);
}
else if(empty($arr[$key]))
{
unset($arr[$key]);
}
}
return $arr;
}
It's a recursive function (so it can be a little brutal on memory with large nested array trees, and this particular one cannot handle infinite recursion (i.e.: circular reference).) But with a non-infinite recursion, and reasonably sized nested array trees, it should work pretty well. It can also be expanded to handle nested object properties as well, but that seemed outside scope. The part where it decides if it's empty is that if(empty()) so you can change that back to that is_null or empty string block.
(Edit: Adding really Low level explanation: loops through the array, if it finds an array inside of that array, it calls itself and repeats the process.)

Categories