checking if a value is a multidimensional array [duplicate] - php

This question already has answers here:
Checking if array is multidimensional or not?
(16 answers)
Closed 9 years ago.
How come when I run this code, I get an output of I am a multidimensional array! (the first block). I thought it would go into the second block, but it doesn't. What am I missing here?
$values = array('1','2');
if(isset($values[0][0])){
echo "I am a multidimensional array!";
}else{
echo "I am not a multidimensional array.";
}

$values = array(1,array(1,2));
$multi = false;
if(is_array($values)){
foreach($values as $k=>$v){
if(is_array($v)){
$multi = true;
break;
}
}
}
echo $multi ? "multi" : "not multi";

Try this:
if(is_array($values[0]))
Edit: This will check the first element of the array only. You should loop through each element to check if its truly multidimensional.
This code checks to see if the first element of the array is also an array. isset just checks whether or not a variable is NULL.
isset in your example is not working as expected. Perhaps there is a slight difference in functionality between PHP versions or setups. I didn't see anything in the manual but maybe you can:
http://php.net/manual/en/function.isset.php
Using is_array is more semantic, so in my opinion is a much better choice.

This code only goes into the if-branch for me, if the first value in the array is explicitly declared as a string,
$values = array('1',2);
– and with that the behavior is nothing but logical, because $values[0] is that text literal '1', and that has a first character that can be access using a zero based index.
So I guess either your real data is of a string type – or it maybe depends in the PHP version (I tested under 5.3.16).
Anyway, using is_array as the other answers already suggested is the right way to go here.

Related

PHP - Remove and return an element from an associative array [duplicate]

This question already has answers here:
How to delete a key and return the value from a PHP array?
(4 answers)
Closed 4 years ago.
Is there a native PHP function for removing an element from an associative array, and returning the value?
Like unset() but with a return value, or array_shift() where you can specify the index to shift?
$element = unset($array['index']);
$element = array_shift($array, 'index');
I know it's easy to do, I'm just curious if there's an elegant one-liner for doing this.
Looking quickly at the official PHP documentation, in the current version (7.2) doesn't have a function that removes and returns an element by the key.
But as you mentioned there are several ways to solve this problem. As you can see at: https://stackoverflow.com/a/10898827/4214312

Set Array Equal to Another Array without Specified Key/Values [duplicate]

This question already has answers here:
php array difference against keys of an array and an array of keys?
(3 answers)
Unset elements using array keys
(2 answers)
Closed 5 years ago.
I am attempting to mirror the behavior of newArray = oldArray, with the caveat of excluding some key/values of the oldArray, so something like newArray = oldArray - undesiredOldKeyValue. I realize this is fully doable with a foreach on the oldArray and using an if to see if the encountered key is desired or not, but I am interested in a simpler or more concise approach if possible.
A couple of things to keep in mind, I need to exclude key/value pairs based on key, not value. I do not want to modify the oldArray in the process of doing this.
You may try to use array_filer. Something like:
$new_array = array_filter($old_array, function ($value, $key) {
// return false if you don't want a value, true if you want it.
// Example 1: `return $value != 'do not keep this one';`
// Example 2: `return !in_array($key, ['unwanted-key1', 'unwanted-key2', 'etc']);`
}, ARRAY_FILTER_USE_BOTH);
It will filters elements of an array using a callback function.

Php Unset All Keys [duplicate]

This question already has answers here:
For cleared or unset php arrays, are elements garbage collected?
(3 answers)
Closed 8 years ago.
My question might seems basic but still, can't figure how to works this out.
Consider an array of my favorite fruits
$array = array("Banana","Rasberry","Blackberry")
I'm looking to clear this array so that all keys and values would be erased. My array would be empty just like if I had wrote
$array = array();
Then, I could array_push some new data in.
I thought that I could array_walk($array, unset($array[$key]) but it's not working properly.
Your question includes the best solution for your situation:
$array = array();
This is the fastest way to make the $array variable point to an empty array.

One line code to get one value from function that returns an array [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Parse error on explode('-','foo-bar')[0] (for instance)
In PHP there are functions that return an array, for example:
$a = parse_url("https://stackoverflow.com/q/9461027/87015");
echo $a["host"]; // stackoverflow.com
My question is how to combine the above two statements into a single statement. This (is something that works in JavaScript but) does not work:
echo parse_url("https://stackoverflow.com/q/9461027/87015")["host"];
Note: function array dereferencing is available since PHP 5.4; the above code works as-is.
You can do a little trick instead, write a simple function
function readArr($array, $index) {
return $array[$index];
}
Then use it like this
echo readArr(parse_url("http://stackoverflow.com/questions/9458303/how-can-i-change-the-color-white-from-a-uiimage-to-transparent"),"host");
Honestly, the best way of writing your above code is:
$a = parse_url("http://stackoverflow.com/q/9461027/87015");
echo $a["scheme"];
echo $a["host"];
Isn't that what I originally posted?
Yes. Depending on context you may want a better name than $a (perhaps $url), but that is the best way to write it. Adding a function is not an attractive option because when you revisit your code or when someone reads your code, they have to find the obscure function and figure out why on earth it exists. Leave it in the native language in this case.
Alternate code:
You can, however, combine the echo statements:
$a = parse_url("http://stackoverflow.com/q/9461027/87015");
echo $a['scheme'], $a['host'];

conditional statements as strings [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
echo inside if loop
I trying to code a trading system and i have a list of entry and exit strategies. To lessen the number of lines in the code I planned to put all my strategies into an array for each entry and exit. My array is like this
$enter_strats = array(
array('name'=>"macd",'strat'=>"/$divergence[/$key]>0.1;"),
);
I am including the conditional statements inside the array as above.
while I am looping thru everyday prices, I have to check for each entry strategy if they they are true. My if statement is like this
foreach($divergence as $key=>$value)
{
if($trade ==0)
{
foreach($enter_strats as $k =>$v)
{
$strat = $v['strat'];
$strat = str_replace("#","$",$strat);
eval("\$strat = \"$strat\";");
if ($strat)
{
$trade =1;
$book->save($key,$close[$key],$v['name']);
}
}
}
}
The problem since it is a string its always if is always evaluating it to true. I tried to put one more eval inside if but its of no use.
Please help to solve this problem, its is very essential. Thanks a lot.
That's because you're trying to lessen the number of lines in the code.
Arrays intended to keep data, not code.
As soon as you understand it, your code will be okay.
'strat' should contain only data. An operator and a number for instance.
keeping variable name in the string makes no sense.
especially if you have this variable already.
You have already have $divergence[$key] in your code.
So, 'strat' should be just array('>',0.1)

Categories