Does foreach() work for non-numerical array keys? - php

I was wondering if foreach() works when the array looks like this:
arr_name[eggs] = something
arr_name[pencil] = something else
Will foreach work if run as:
foreach(arr_name as $key => $value)
for they keys that have a non-numerical value ?

Yes, foreach supports any kind of key. In your case, $key will be a string, 'eggs' and 'pencil' respectively for each item. In fact, foreach was intended for use with arrays that have non-numerical keys which you can't easily iterate using for.

Yes, PHP has no real distinction between arrays with numeric vs non-numeric keys. They're all simply arrays as far as PHP is concerned.

Yes the explanation given by BoltClock is right & i would suggest you to manually try too. You have missed $before array name in the foreach statement
foreach($arr_name as $key=>$value)
echo $value
?>

Related

How do I clear the values in a PHP array while maintaining its keys?

I would like to take an array and clear all of its values while maintaining its keys. By "clear" I mean replace with an empty type value, such as '' or null. PHP obviously has quite a few array functions, but I didn't find anything there that does exactly this. I am currently doing it this way:
foreach ($array as &$value) $value = ''
My question is, is there some built-in php function I overlooked, or any other way I can accomplish this without iterating over the array at this level?
Without knowing exactly what your memory/performance/object-management needs are, it's hard to say what's best. Here are some "I just want something short" alternatives:
$array = array_fill_keys(array_keys($a),""); // Simple, right?
$array = array_map(function(){return "";},$a); // More flexible but easier to typo
If you have an array that's being passed around by reference and really want to wipe it, direct iteration is probably your best bet.
foreach($a as $k => $v){
$a[$k] = "";
}
Iteration with references:
/* This variation is a little more dangerous, because $v will linger around
* and can cause bizarre bugs if you reuse the same variable name later on,
* so make sure you unset() it when you're done.
*/
foreach($a as $k => &$v){
$v = "";
}
unset($v);
If you have a performance need, I suggest you benchmark these yourself with appropriately-sized arrays and PHP versions.
Easiest way is array_map
$array = array_map(function($x) { return '';}, $array);
You can use array_keys to get the keys. You can then use array_flip if you like, although this will assign the values 0 through length-1 to the keys.
There is no single built-in function for this. You might try:
array_combine(array_keys($array),array_fill(0,count($array)-1,""));
But really the code you have right now does the job just fine.

json decode and encode - iterate through multi dimensional array and remove key value if equals certain value

Basically the json output is this -output is from php.
[{"attr":{"id":"node_2","rel":"default"},"data":"C:","state":"closed"},{"attr":{"id":"node_3","rel":"drive"},"data":"D:","state":"closed"}]
so because rel is equal to default
{"attr":{"id":"node_2","rel":"default"},"data":"C:","state":"closed"}
I need to remove this from the array.
I have thought of maybe using
foreach($arr as $key => &$item) {
if ($value['rel'] == 'default'{
unset($arr[$key]);
This however, wont work for some reason. I have no idea if my method is the best way, or whether there is a better way to achieve this.
I also need to decode and encode it.
You can use json_encode and json_decode to parse the json as Jesse Bunch said.
After i decoded the json you posted, it returned as an object. To call on an object you have to do things a bit diffrent.
$arr = json_decode('[{"attr":{"id":"node_2","rel":"default"},"data":"C:","state":"closed"},{"attr":{"id":"node_3","rel":"drive"},"data":"D:","state":"closed"}]');
foreach($arr as $key => $row)
{
if ($row->attr->rel == 'default'){
unset($arr[$key]);
}
}
var_dump($arr);
The $arr does no longer contain the default rel
In most languages, mutating an array while you're looping it is frowned upon. In PHP, there is nothing that say you cannot mutate an array while looping it. What you're doing is absolutely fine and probably the most efficient way of doing it.
As for encoding and decoding, see json_encode and json_decode.

Grabbing the name from data sent through post

When I send over post data I do a print_r($_POST); and I get something like this...
Array ( [gp1] => 9 )
Is there a way to get the "gp1", the name sent over as a value? I tried doing.
echo key($_POST["gp1"]);
But no luck there, I figured it would echo gp1. Is there a way to do this?
you need
print_r(array_keys($_POST));
check this for more details http://php.net/manual/en/function.array-keys.php
You could use foreach to see each key-value pair, or use array_keys to get a list of all keys.
foreach ($_POST as $key => $value) {
// Do whatever
}
Well, if you can write $_POST["gp1"] you already have the key anyway ;)
key() works differently, it takes an array as argument:
The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL.
So if you have not done anything with the array (no traversing), key($_POST) would give you the key of the first element of the array.
Maybe you want a foreach loop?
foreach($_POST as $key => $value) {
}
There are other methods to retrieve keys as to well. It depends on what you want to do.

looping through a session array

Hello i got a question, i have a session array called 'addToCart', in there are multiple arrays with various id's, i would like to loop through these arrays with a foreach regardless of what the id name is. Does anyone know how i would approach this?
Does the following construction satisfy your needs?
foreach ($addToChart as $key=>$value){
// do anything you want with $key and $value
}
If you need to check "sub-arrays", you can check $value with is_array() function and add one more foreach loop inside.

multidimensional array

Please explain what is the meaning of
foreach ($toplist['children'] as $subkey => $subname)
and where the children come from. I'm confused.
Basically $toplist is an array of values. One of those values has been called 'children'.
In this case, the value at position 'children' is itself an array.
Your line of code is telling the computer to loop over each of the values inside the 'children' array and extract the key and value.
$subkey is the key, $subname is the name.
In other words, $toplist['children'][$subkey] == $subvalue
The other elements are coming from the $toplist['children'] array which you got to figure out where it is coming from since you have not put in all the needed code for the question. See this about foreach machenism to learn more about it.
his simply gives an easy way to
iterate over arrays. foreach works
only on arrays, and will issue an
error when you try to use it on a
variable with a different data type or
an uninitialized variable.
php.net

Categories