PHP variable variable array key list - php

I have a multidimensional array where this works:
print_r( $temp[1][0] );
How can I make this work... I have the list of keys as a string like this:
$keys = "[1][0]";
I want to access the array using the string list of keys, how can it be done?
This works but the keys are obviously hard coded:
$keys = "[1][0]";
$tempName = 'temp';
print_r( ${$tempName}[1][0] );
// tried lots of variations like, but they all produce errors or don't access the array
print_r( ${$tempName.${$keys}} );
Thanks,
Chris

function accessArray(array $array, $keys) {
if (!preg_match_all('~\[([^\]]+)\]~', $keys, $matches, PREG_PATTERN_ORDER)) {
throw new InvalidArgumentException;
}
$keys = $matches[1];
$current = $array;
foreach ($keys as $key) {
$current = $current[$key];
}
return $current;
}
echo accessArray(
array(
1 => array(
2 => 'foo'
)
),
'[1][2]'
); // echos 'foo'
Would be even nicer, if you passed in array(1, 2), instead of [1][2]: One could avoid the (fragile) preg_match_all parsing.

Related

replace all keys in php array

This is my array:
['apple']['some code']
['beta']['other code']
['cat']['other code 2 ']
how can I replace all the "e" letters with "!" in the key name and keep the values
so that I will get something like that
['appl!']['some code']
['b!ta']['other code']
['cat']['other code 2 ']
I found this but because I don't have the same name for all keys I can't use It
$tags = array_map(function($tag) {
return array(
'name' => $tag['name'],
'value' => $tag['url']
);
}, $tags);
I hope your array looks like this:-
Array
(
[apple] => some code
[beta] => other code
[cat] => other code 2
)
If yes then you can do it like below:-
$next_array = array();
foreach ($array as $key=>$val){
$next_array[str_replace('e','!',$key)] = $val;
}
echo "<pre/>";print_r($next_array);
output:- https://eval.in/780144
You can stick with array_map actually. It is not really practical, but as a prove of concept, this can be done like this:
$array = array_combine(
array_map(function ($key) {
return str_replace('e', '!', $key);
}, array_keys($array)),
$array
);
We use array_keys function to extract keys and feed them to array_map. Then we use array_combine to put keys back to place.
Here is working demo.
Here we are using array_walk and through out the iteration we are replacing e to ! in key and putting the key and value in a new array.
Try this code snippet here
<?php
$firstArray = array('apple'=>'some code','beta'=>'other code','cat'=>'other code 2 ');
$result=array();
array_walk($firstArray, function($value,$key) use (&$result) {
$result[str_replace("e", "!", $key)]=$value;
});
print_r($result);
If you got this :
$firstArray = array('apple'=>'some code','beta'=>'other code','cat'=>'other code 2 ');
You can try this :
$keys = array_keys($firstArray);
$outputArray = array();
$length = count($firstArray);
for($i = 0; $i < $length; $i++)
{
$key = str_replace("e", "!", $keys[ $i ]);
$outputArray[ $key ] = $firstArray[$keys[$i]];
}
We can iterate the array and mark all problematic keys to be changed. Check for the value whether it is string and if so, make sure the replacement is done if needed. If it is an array instead of a string, then call the function recursively for the inner array. When the values are resolved, do the key replacements and remove the bad keys. In your case pass "e" for $old and "!" for $new. (untested)
function replaceKeyValue(&$arr, $old, $new) {
$itemsToRemove = array();
$itemsToAdd = array();
foreach($arr as $key => $value) {
if (strpos($key, $old) !== false) {
$itemsToRemove[]=$key;
$itemsToAdd[]=str_replace($old,$new,$key);
}
if (is_string($value)) {
if (strpos($value, $old) !== false) {
$arr[$key] = str_replace($old, $new, $value);
}
} else if (is_array($value)) {
$arr[$key] = replaceKeyValue($arr[$key], $old, $new);
}
}
for ($index = 0; $index < count($itemsToRemove); $index++) {
$arr[$itemsToAdd[$index]] = $itemsToRemove[$index];
unset($arr[$itemsToRemove[$index]]);
}
return $arr;
}
Another option using just 2 lines of code:
Given:
$array
(
[apple] => some code
[beta] => other code
[cat] => other code 2
)
Do:
$replacedKeys = str_replace('e', '!', array_keys($array));
return array_combine($replacedKeys, $array);
Explanation:
str_replace can take an array and perform the replace on each entry. So..
array_keys will pull out the keys (https://www.php.net/manual/en/function.array-keys.php)
str_replace will perform the replacements (https://www.php.net/manual/en/function.str-replace.php)
array_combine will rebuild the array using the keys from the newly updated keys with the values from the original array (https://www.php.net/manual/en/function.array-combine.php)

array values to nested array with PHP

I'm trying to figure out how I can use the values an indexed array as path for another array. I'm exploding a string to an array, and based on all values in that array I'm looking for a value in another array.
Example:
$haystack['my']['string']['is']['nested'] = 'Hello';
$var = 'my#string#is#nested';
$items = explode('#', $var);
// .. echo $haystack[... items..?]
The number of values may differ, so it's not an option to do just $haystack[$items[0][$items[1][$items[2][$items[3]].
Any suggestions?
You can use a loop -
$haystack['my']['string']['is']['nested'] = 'Hello';
$var = 'my#string#is#nested';
$items = explode('#', $var);
$temp = $haystack;
foreach($items as $v) {
$temp = $temp[$v]; // Store the current array value
}
echo $temp;
DEMO
You can use a loop to grab each subsequent nested array. I.e:
$haystack['my']['string']['is']['nested'] = 'Hello';
$var = 'my#string#is#nested';
$items = explode('#', $var);
$val = $haystack;
foreach($items as $key){
$val = $val[$key];
}
echo $val;
Note that this does no checking, you likely want to check that $val[$key] exists.
Example here: http://codepad.org/5ei9xS91
Or you can use a recursive function:
function extractValue($array, $keys)
{
return empty($keys) ? $array : extractValue($array[array_shift($keys)], $keys) ;
}
$haystack = array('my' => array('string' => array('is' => array('nested' => 'hello'))));
echo extractValue($haystack, explode('#', 'my#string#is#nested'));

how to get all keys that lead to given value when iterating multilevel array in php

Example:
$arr = array(array("name"=>"Bob","species"=>"human","children"=>array(array("name"=>"Alice","age"=>10),array("name"=>"Jane","age"=>13)),array("name"=>"Sparky","species"=>"dog")));
print_r($arr);
array_walk_recursive($arr, function($v,$k) {
echo "key: $k\n";
});
The thing here is that I get only the last key, but I have no way to refer where I been, that is to store a particular key and change value after I left the function or change identical placed value in another identical array.
What I would have to get instead of string is an array that would have all keys leading to given value, for example [0,"children",1,"age"].
Edit:
This array is only example. I've asked if there is universal way to iterate nested array in PHP and get full location path not only last key. And I know that there is a way of doing this by creating nested loops reflecting structure of the array. But I repeat: I don't know the array structure in advance.
To solve your problem you will need recursion. The following code will do what you want, it will also find multiple paths if they exists:
$arr = array(
array(
"name"=>"Bob",
"species"=>"human",
"children"=>array(
array(
"name"=>"Alice",
"age"=>10
),
array(
"name"=>"Jane",
"age"=>13
)
),
array(
"name"=>"Sparky",
"species"=>"dog"
)
)
);
function getPaths($array, $search, &$paths, $currentPath = array()) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$currentPath[] = $key;
if (true !== getPaths($value, $search, $paths, $currentPath)) {
array_pop($currentPath);
}
} else {
if ($search == $value) {
$currentPath[] = $key;
$paths[] = $currentPath;
return true;
}
}
}
}
$paths = array();
getPaths($arr, 13, $paths);
print_r($paths);

How do I remove specific keys from Array? PHP

I am trying to remove keys from array.
Here is what i get from printing print_r($cats);
Array
(
[0] => All > Computer errors > HTTP status codes > Internet terminology
[1] =>
Main
)
I am trying to use this to remove "Main" category from the array
function array_cleanup( $array, $todelete )
{
foreach( $array as $key )
{
if ( in_array( $key[ 'Main' ], $todelete ) )
unset( $array[ $key ] );
}
return $array;
}
$newarray = array_cleanup( $cats, array('Main') );
Just FYI I am new to PHP... obviously i see that i made mistakes, but i already tried out many things and they just don't seem to work
Main is not the element of array, its a part of a element of array
function array_cleanup( $array, $todelete )
{
$cloneArray = $array;
foreach( $cloneArray as $key => $value )
{
if (strpos($value, $todelete ) !== false)
unset( $array[ $key ] ); //$array[$key] = str_replace($toDelete, $replaceWith, $value) ; // add one more argument $replaceWith to function
}
return $array;
}
Edit:
with array
function array_cleanup( $array, $todelete )
{
foreach($todelete as $del){
$cloneArray = $array;
foreach( $cloneArray as $key => $value )
{
if (strpos($value, $del ) !== false)
unset( $array[ $key ] ); //$array[$key] = str_replace($toDelete, $replaceWith, $value) ; // add one more argument $replaceWith to function
}
}
return $array;
}
$newarray = array_cleanup( $cats, array('Category:Main') );
Wanted to note that while the accepted answer works there's a built in PHP function that handles this called array_filter. For this particular example it'd be something like:
public function arrayRemoveMain($var){
if ( strpos( $var, "Category:Main" ) !== false ) { return false; }
return true;
}
$newarray = array_filter( $cats, "arrayRemoveMain" );
Obviously there are many ways to do this, and the accepted answer may very well be the most ideal situation especially if there are a large number of $todelete options. With the built in array_filter I'm not aware of a way to pass additional parameters like $todelete so a new function would have to be created for each option.
It's easy.
$times = ['08:00' => '08:00','09:00' => '09:00','10:00' => '10:00'];
$timesReserved = ['08:00'];
$times = (function() use ($times, $timesReserved) {
foreach($timesReserved as $time){
unset($times[$time]);
}
return $times;
})();
The question is "how do I remove specific keys".. So here's an answer with array filter if you're looking to eliminate keys that contain a specific string, in our example if we want to eliminate anything that contains "alt_"
$arr = array(
"alt_1"=>"val",
"alt_2" => "val",
"good key" => "val"
);
function remove_alt($k) {
if(strpos($k, "alt_") !== false) {
# return false if there's an "alt_" (won't pass array_filter)
return false;
} else {
# all good, return true (let it pass array_filter)
return true;
}
}
$new = array_filter($arr,"remove_alt",ARRAY_FILTER_USE_KEY);
# ^ this tells the script to enable the usage of array keys!
This will return
array(""good key" => "val");

How to find a value in an array and remove it by using PHP array functions?

How to find if a value exists in an array and then remove it? After removing I need the sequential index order.
Are there any PHP built-in array functions for doing this?
<?php
$my_array = array('sheldon', 'leonard', 'howard', 'penny');
$to_remove = array('howard');
$result = array_diff($my_array, $to_remove);
?>
To search an element in an array, you can use array_search function and to remove an element from an array you can use unset function. Ex:
<?php
$hackers = array ('Alan Kay', 'Peter Norvig', 'Linus Trovalds', 'Larry Page');
print_r($hackers);
// Search
$pos = array_search('Linus Trovalds', $hackers);
// array_seearch returns false if an element is not found
// so we need to do a strict check here to make sure
if ($pos !== false) {
echo 'Linus Trovalds found at: ' . $pos;
// Remove from array
unset($hackers[$pos]);
}
print_r($hackers);
You can refer: https://www.php.net/manual/en/ref.array.php for more array related functions.
You need to find the key of the array first, this can be done using array_search()
Once done, use the unset()
<?php
$array = array( 'apple', 'orange', 'pear' );
unset( $array[array_search( 'orange', $array )] );
?>
Just in case you want to use any of mentioned codes, be aware that array_search returns FALSE when the "needle" is not found in "haystack" and therefore these samples would unset the first (zero-indexed) item. Use this instead:
<?php
$haystack = Array('one', 'two', 'three');
if (($key = array_search('four', $haystack)) !== FALSE) {
unset($haystack[$key]);
}
var_dump($haystack);
The above example will output:
Array
(
[0] => one
[1] => two
[2] => three
)
And that's good!
You can use array_filter to filter out elements of an array based on a callback function. The callback function takes each element of the array as an argument and you simply return false if that element should be removed. This also has the benefit of removing duplicate values since it scans the entire array.
You can use it like this:
$myArray = array('apple', 'orange', 'banana', 'plum', 'banana');
$output = array_filter($myArray, function($value) { return $value !== 'banana'; });
// content of $output after previous line:
// $output = array('apple', 'orange', 'plum');
And if you want to re-index the array, you can pass the result to array_values like this:
$output = array_values($output);
This solution is the combination of #Peter's solution for deleting multiple occurences and #chyno solution for removing first occurence. That's it what I'm using.
/**
* #param array $haystack
* #param mixed $value
* #param bool $only_first
* #return array
*/
function array_remove_values(array $haystack, $needle = null, $only_first = false)
{
if (!is_bool($only_first)) { throw new Exception("The parameter 'only_first' must have type boolean."); }
if (empty($haystack)) { return $haystack; }
if ($only_first) { // remove the first found value
if (($pos = array_search($needle, $haystack)) !== false) {
unset($haystack[$pos]);
}
} else { // remove all occurences of 'needle'
$haystack = array_diff($haystack, array($needle));
}
return $haystack;
}
Also have a look here: PHP array delete by value (not key)
The unset array_search has some pretty terrible side effects because it can accidentally strip the first element off your array regardless of the value:
// bad side effects
$a = [0,1,2,3,4,5];
unset($a[array_search(3, $a)]);
unset($a[array_search(6, $a)]);
$this->log_json($a);
// result: [1,2,4,5]
// what? where is 0?
// it was removed because false is interpreted as 0
// goodness
$b = [0,1,2,3,4,5];
$b = array_diff($b, [3,6]);
$this->log_json($b);
// result: [0,1,2,4,5]
If you know that the value is guaranteed to be in the array, go for it, but I think the array_diff is far safer. (I'm using php7)
$data_arr = array('hello', 'developer', 'laravel' );
// We Have to remove Value "hello" from the array
// Check if the value is exists in the array
if (array_search('hello', $data_arr ) !== false) {
$key = array_search('hello', $data_arr );
unset( $data_arr[$key] );
}
# output:
// It will Return unsorted Indexed array
print( $data_arr )
// To Sort Array index use this
$data_arr = array_values( $data_arr );
// Now the array key is sorted
First of all, as others mentioned, you will be using the "array_search()" & the "unset()" methodsas shown below:-
<?php
$arrayDummy = array( 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg' );
unset( $arrayDummy[array_search( 'dddd', $arrayDummy )] ); // Index 3 is getting unset here.
print_r( $arrayDummy ); // This will show the indexes as 0, 1, 2, 4, 5, 6.
?>
Now to re-index the same array, without sorting any of the array values, you will need to use the "array_values()" method as shown below:-
<?php
$arrayDummy = array_values( $arrayDummy );
print_r( $arrayDummy ); // Now, you will see the indexes as 0, 1, 2, 3, 4, 5.
?>
Hope it helps.
Okay, this is a bit longer, but does a couple of cool things.
I was trying to filter a list of emails but exclude certain domains and emails.
Script below will...
Remove any records with a certain domain
Remove any email with an exact value.
First you need an array with a list of emails and then you can add certain domains or individual email accounts to exclusion lists.
Then it will output a list of clean records at the end.
//list of domains to exclude
$excluded_domains = array(
"domain1.com",
);
//list of emails to exclude
$excluded_emails = array(
"bob#domain2.com",
"joe#domain3.com",
);
function get_domain($email) {
$domain = explode("#", $email);
$domain = $domain[1];
return $domain;
}
//loop through list of emails
foreach($emails as $email) {
//set false flag
$exclude = false;
//extract the domain from the email
$domain = get_domain($email);
//check if the domain is in the exclude domains list
if(in_array($domain, $excluded_domains)){
$exclude = true;
}
//check if the domain is in the exclude emails list
if(in_array($email, $excluded_emails)){
$exclude = true;
}
//if its not excluded add it to the final array
if($exclude == false) {
$clean_email_list[] = $email;
}
$count = $count + 1;
}
print_r($clean_email_list);
To find and remove multiple instance of value in an array, i have used the below code
$list = array(1,3,4,1,3,1,5,8);
$new_arr=array();
foreach($list as $value){
if($value=='1')
{
continue;
}
else
{
$new_arr[]=$value;
}
}
print_r($new_arr);

Categories