getting variables from an array where some variables are arrays - php

I am struggling of getting values extracted from an array where some values are values and some values are arrays.
global $globals;
foreach($globals as $value)
{
if ($value == "array")
{
global $$value = array;
}
else
{
global $$value;
}
}
Everything is fine except this part: global $$value = array; How to foreach $value as array?

Perhaps you could make use of the PHP is_array function ?
http://php.net/manual/en/function.is-array.php
e.g.
if(is_array($value)) {
echo 'Is Array';
} else {
echo 'not an Array';
}

I think what you're trying to accomplish is to check if any $value in the $globals is array or not, for that you may use is_array and use for each as per your needs.
foreach($globals as $value)
{
if (is_array($value)){
foreach ($value as $new_value) {
# Your job
}
}
//
//other codes
}

Related

PHP Array Search with key values

I have following arrays :
<?php
$a=array(
"abc"=>array("red","white","orange"),
"def"=>array("green","vilot","yellow"),
"xyz"=>array("blue","dark","pure")
);
echo array_search(array("dark"),$a);
?>
How to get output of xyz in array list.
array_search returns false or the key. Since you have multiple dimensions you must loop through to get the lowest level.
Since we are in another dimension your return will actually be 1. For this reason, if array_search succeeds we must use the key that is defined in the foreach
<?php
$a=array("abc"=>array("red","white","orange"),"def"=>array("green","vilot","yellow"),"xyz"=>array("blue","dark","pure"));
foreach($a as $key=>$data){
if(array_search("dark",$data)){
echo $key;
}
}
Outputs: xyz
You can create one user-define function to check value
$a=array("abc"=>array("red","white","orange"),"def"=>array("green","vilot","yellow"),"xyz"=>array("blue","dark","pure"));
function search_data($value, $array) {
foreach ($array as $key => $val) {
if(is_array($val) && in_array($value,$val))
{
return $key;
}
}
return null;
}
echo search_data("dark",$a);
DEMO
Please try this
function searchMultiArray($arrayVal,$val){
foreach($arrayVal as $key => $suba){
if (in_array($val, $suba)) {
return $key;
}
}
}
$a = array("abc"=>array("red","white","orange"),"def"=>array("green","vilot","yellow"),"xyz"=>array("blue","dark","pure"));
echo $keyVal = searchMultiArray($a , "dark");

Faster way to see if an array contains values besides the one specified

I have an array where each element has a subarray with multiple Ids. When looping through the array, I'd like to check if the subarray has any elements besides a given one.
For example, I'd like to echo 'Yes' whenever one of the subarrays has any ids other than 'TESTID'.
I can do this by looping through the subarray, but I'd like to know of a way that doesn't require double loops.
Here's the current code:
foreach ($elements as $element) {
...
if (besidesInArray('TESTID',$element['ids'])) {
//operations
} else {
//element only has 'TESTID'
}
...
}
...
function besidesInArray($needle, $haystack) {
foreach ($haystack as $hay) {
if($hay != $needle) {
return TRUE;
}
}
return FALSE;
}
While this code works, I'd like to see if there's a more elegant solution.
You can use in_array() function to achieve this
foreach($array as $key => $subarray)
{
if(in_array("TESTID", $subarray))
{
//found
} else {
//not found
}
}
preg_grep for TESTID but invert the grep so that it returns entries NOT matching.
foreach($array as $subarray) {
if(preg_grep("/TESTID/", $subarray, PREG_GREP_INVERT)) {
echo 'Yes'; //others found
}
}
TESTID could be a var instead. Man I love some preg_grep!
find = implode(')|(',$mypatternarray);
find.="(".find.")";
foreach($subarray as $subar){
if(preg_match("find",$subar)>0)){
echo "id found";
}
}

PHP if in array, do something with the value

I am trying to check if a value is in an array. If so, grab that array value and do something with it. How would this be done?
Here's an example of what I'm trying to do:
$the_array = array("buejcxut->10", "jueofi31->20", "nay17dtt->30");
if (in_array('20', $the_array)) {
// If found, assign this value to a string, like $found = 'jueofi31->20'
$found_parts = explode('->', $found);
echo $found_parts['0']; // This would echo "jueofi31"
}
This should do it:
foreach($the_array as $key => $value) {
if(preg_match("#20#", $value)) {
$found_parts = explode('->', $value);
}
echo $found_parts[0];
}
And replace "20" by any value you want.
you might be better off checking it in a foreach loop:
foreach ($the_array as $key => $value) {
if ($value == 20) {
// do something
}
if ($value == 30) {
//do something else
}
}
also you array definitition is strange, did you mean to have:
$the_array = array("buejcxut"=>10, "jueofi31"=>20, "nay17dtt"=>30);
using the array above the $key is the element key (buejcxut, jueofi31, etc) and $value is the value of that element (10, 20, etc).
Here's an example of how you can search the values of arrays with Regular Expressions.
<?php
$the_array = array("buejcxut->10", "jueofi31->20", "nay17dtt->30");
$items = preg_grep('/20$/', $the_array);
if( isset($items[1]) ) {
// If found, assign this value to a string, like $found = 'jueofi31->20'
$found_parts = explode('->', $items[1]);
echo $found_parts['0']; // This would echo "jueofi31"
}
You can see a demo here: http://codepad.org/XClsw0UI
if you want to define an indexed array it should be like this:
$my_array = array("buejcxut"=>10, "jueofi31"=>20, "nay17dtt"=>30);
then you can use in_array
if (in_array("10", $my_array)) {
echo "10 is in the array";
// do something
}

Unset inside array_walk_recursive not working

array_walk_recursive($arr, function(&$val, $key){
if($val == 'smth'){
unset($val); // <- not working, unset($key) doesn't either
$var = null; // <- setting it to null works
}
});
print_r($arr);
I don't want it to be null, I want the element out of the array completely. Is this even possible with array_walk_recursive?
You can't use array_walk_recursive here but you can write your own function. It's easy:
function array_unset_recursive(&$array, $remove) {
$remove = (array)$remove;
foreach ($array as $key => &$value) {
if (in_array($value, $remove)) {
unset($array[$key]);
} elseif (is_array($value)) {
array_unset_recursive($value, $remove);
}
}
}
And usage:
array_unset_recursive($arr, 'smth');
or remove several values:
array_unset_recursive($arr, ['smth', 51]);
unset($val) will only remove the local $val variable.
There is no (sane) way how you can remove an element from the array inside array_walk_recursive. You probably will have to write a custom recursive function to do so.
The answer of #dfsq is correct but this function doesn't remove empty array. So you can end up with Tree of empty array, which is not what is expected in most cases.
I used this modified function instead:
public function array_unset_recursive(&$array, $remove) {
foreach ($array as $key => &$value) {
if (is_array($value)) {
$arraySize = $this->array_unset_recursive($value, $remove);
if (!$arraySize) {
unset($array[$key]);
}
} else if (in_array($key, $remove, true)){
unset($array[$key]);
}
}
return count($array);
}

Access PHP array element with a function?

I'm working on a program that uses PHP's internal array pointers to iterate along a multidimensional array. I need to get an element from the current row, and I've been doing it like so:
$arr[key($arr)]['item']
However, I'd much prefer to use something like:
current($arr)['item'] // invalid syntax
I'm hoping there's a function out there that I've missed in my scan of the documentation that would enable me to access the element like so:
getvalue(current($arr), 'item')
or
current($arr)->getvalue('item')
Any suggestions?
I very much doubt there is such a function, but it's trivial to write
function getvalue($array, $key)
{
return $array[$key];
}
Edit: As of PHP 5.4, you can index array elements directly from function expressions, current($arr)['item'].
Have you tried using one of the iterator classes yet? There might be something in there that does exactly what you want. If not, you can likely get what you want by extending the ArrayObject class.
This function might be a bit lenghty but I use it all the time, specially in scenarious like:
if (array_key_exists('user', $_SESSION) === true)
{
if (array_key_exists('level', $_SESSION['user']) === true)
{
$value = $_SESSION['user']['level'];
}
else
{
$value = 'DEFAULT VALUE IF NOT EXISTS';
}
}
else
{
$value = 'DEFAULT VALUE IF NOT EXISTS';
}
Turns to this:
Value($_SESSION, array('user', 'level'), 'DEFAULT VALUE IF NOT EXISTS');
Here is the function:
function Value($array, $key = 0, $default = false)
{
if (is_array($array) === true)
{
if (is_array($key) === true)
{
foreach ($key as $value)
{
if (array_key_exists($value, $array) === true)
{
$array = $array[$value];
}
else
{
return $default;
}
}
return $array;
}
else if (array_key_exists($key, $array) === true)
{
return $array[$key];
}
}
return $default;
}
PS: You can also use unidimensional arrays, like this:
Value($_SERVER, 'REQUEST_METHOD', 'DEFAULT VALUE IF NOT EXISTS');
If this does not work, how is your multidimensional array composed? A var_dump() might help.
$subkey = 'B';
$arr = array(
$subkey => array(
'AB' => 'A1',
'AC' => 'A2'
)
);
echo current($arr[$subkey]);
next($arr[$subkey]);
echo current($arr[$subkey]);
I often use
foreach ($arr as $key=>$val) {
$val['item'] /*$val is the value of the array*/
$key /*$key is the key used */
}
instead of
next($arr)/current($arr)

Categories