Split array into key => array() - php

Consider the following array:
$array[23] = array(
[0] => 'FOO'
[1] => 'BAR'
[2] => 'BAZ'
);
Whenever I want to work with the inner array, I do something like this:
foreach ($array as $key => $values) {
foreach ($values as $value) {
echo $value;
}
}
The outer foreach-loop is there to split the $key and $value-pairs of $array. This works fine for arrays with many keys ([23], [24], ...)but seems redundant if you know beforehand that $array only has one key (23 in this case). In a case as such, isn't there a better way to split the key from the values? Something like
split($array into $key => $values)
foreach ($values as $value) {
echo $value;
}
I hope I made myself clear.

reset returns the first element of you array and key returns its key:
$your_inner_arr = reset($array);
$your_key = key($array);

Yea, just get rid of your first foreach and define the array you're using with the known $key of your outter array.
foreach ($array[23] as $key =>$val):
//do whatever you want in here
endforeach;

If an array has only one element, you can get it with reset:
$ar = array(23 => array('foo', 'bar'));
$firstElement = reset($ar);

A very succinct approach would be
foreach(array_shift($array) as $item) {
echo $item;
}

Related

PHP array unset string

I am trying to unset a group of array keys that have the same prefix. I can't seem to get this to work.
foreach ($array as $key => $value) {
unset($array['prefix_' . $key]);
}
How can I get unset to see ['prefix_' . $key] as the actual variable? Thanks
UPDATE: The $array keys will have two keys with the same name. Just one will have the prefix and there are about 5 keys with prefixed keys:
Array {
[name] => name
[prefix_name] => other name
}
I don't want to remove [name] just [prefix_name] from the array.
This works:
$array = array(
'aa' => 'other value aa',
'prefix_aa' => 'value aa',
'bb' => 'other value bb',
'prefix_bb' => 'value bb'
);
$prefix = 'prefix_';
foreach ($array as $key => $value) {
if (substr($key, 0, strlen($prefix)) == $prefix) {
unset($array[$key]);
}
}
If you copy/paste this code at a site like http://writecodeonline.com/php/, you can see for yourself that it works.
You can't use a foreach because it's only a copy of the collection. You'd need to use a for or grab the keys separately and separate your processing from the array you want to manipulate. Something like:
foreach (array_keys($array) as $keyName){
if (strncmp($keyName,'prefix_',7) === 0){
unset($array[$keyName]);
}
}
You're also already iterating over the collection getting every key. Unless you had:
$array = array(
'foo' => 1,
'prefix_foo' => 1
);
(Where every key also has a matching key with "prefix_" in front of it) you'll run in to trouble.
I'm not sure I understand your question, but if you are trying to unset all the keys with a specific prefix, you can iterate through the array and just unset the ones that match the prefix.
Something like:
<?php
foreach ($array as $key => $value) { // loop through keys
if (preg_match('/^prefix_/', $key)) { // if the key stars with 'prefix_'
unset($array[$key]); // unset it
}
}
You're looping over the array keys already, so if you've got
$array = (
'prefix_a' => 'b',
'prefix_c' => 'd'
etc...
)
Then $keys will be prefix_a, prefix_c, etc... What you're doing is generating an entirely NEW key, which'd be prefix_prefix_a, prefix_prefix_c, etc...
Unless you're doing something more complicated, you could just replace the whole loop with
$array = array();
I believe this should work:
foreach ($array as $key => $value) {
unset($array['prefix_' . str_replace('prefix_', '', $key]);
}

Retrieve array key passed on value PHP

I have the following array
$group= array(
[0] => 'apple',
[1] => 'orange',
[2] => 'gorilla'
);
I run the array group through an for each function and when the loop hits values of gorilla I want it to spit out the index of gorilla
foreach ($group as $key) {
if ($key == gorilla){
echo //<------ the index of gorilla
}
}
You can use array_search function to get the key for specified value:
$key = array_search('gorilla', $group);
foreach( $group as $index => $value) {
if ($value == "gorilla")
{
echo "The index is: $index";
}
}
array_search — Searches the array for a given value and returns the corresponding key if successful
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>
foreach($group as $key => $value) {
if ($value=='gorilla') {
echo $key;
}
}
The foreach($c as $k => $v) syntax is similar to the foreach($c as $v) syntax, but it puts the corresponding keys/indices in $k (or whatever variable is placed there) for each value $v in the collection.
However, if you're just looking for the index of a single value, array_search() may be simpler. If you're looking for indices for many values, stick with the foreach.
Try this:
foreach ($group as $key => $value)
{
echo "$key points to $value";
}
foreach documentation on php.net

PHP Key name array

I have an array $data
fruit => apple,
seat => sofa,
etc. I want to loop through so that each key becomes type_key[0]['value'] so eg
type_fruit[0]['value'] => apple,
type_seat[0]['value'] => sofa,
and what I thought would do this, namely
foreach ($data as $key => $value)
{
# Create a new, renamed, key.
$array[str_replace("/(.+)/", "type_$1[0]['value']", $key)] = $value;
# Destroy the old key/value pair
unset($array[$key]);
}
print_r($array);
Doesn't work. How can I make it work?
Also, I want everything to be in the keys (not the values) to be lowercase: is there an easy way of doing this too? Thanks.
Do you mean you want to make the keys into separate arrays? Or did you mean to just change the keys in the same array?
$array = array();
foreach ($data as $key => $value)
{
$array['type_' . strtolower($key)] = array(array('value' => $value));
}
if you want your keys to be separate variables, then do this:
extract($array);
Now you will have $type_fruit and $type_sofa. You can find your values as $type_fruit[0]['value'], since we put an extra nested array in there.
Your requirements sound... suspect. Perhaps you meant something like the following:
$arr = array('fruit' => 'apple', 'seat' => 'sofa');
$newarr = array();
foreach ($arr as $key => $value)
{
$newkey = strtolower("type_$key");
$newarr[$newkey] = array(array('value' => $value));
}
var_dump($newarr);
First I wouldn't alter the input-array but create a new one unless you're in serious, serious trouble with your memory limit.
And then you can't simply replace the key to add a deeper nested level to an array.
$x[ 'abc[def]' ] is still only referencing a top-level element, since abc[def] is parsed as one string, but you want $x['abc']['def'].
$data = array(
'fruit' => 'apple',
'seat' => 'sofa'
);
$result = array();
foreach($data as $key=>$value) {
$target = 'type_'.$key;
// this might be superfluous, but who knows... if you want to process more than one array this might be an issue.
if ( !isset($result[$target]) || !is_array($result[$target]) ) {
$result[$target] = array();
}
$result[$target][] = array('value'=>$value);
}
var_dump($result);
for starters
$array[str_replace("/(.+)/", "type_$1[0]['value']", $key)] = $value;
should be
$array[str_replace("/(.+)/", type_$1[0]['value'], $key)] = $value;

In PHP how do i update values in an asssociative array and store the entire array?

Here's a code example:
$array = array();
$array['master']['slave'] = "foo";
foreach ($array as $key => $value) {
foreach ($value as $key2 => $value2) {
if (preg_match('/slave/',$key2)) {
$value[$key2] = "bar";
print "$value[$key2] => $key2 => $value2\n";
}
}
}
print_r($array);
Output:
bar => slave => foo
Array
(
[master] => Array
(
[slave] => foo
)
)
Rather i would like to have the following as the final array:
Array
(
[master] => Array
(
[slave] => bar
)
)
What wrong am i doing here?
Thank you!
Note:
Example2:
$a= array('l1'=>array('l2'=>array('l3'=>array('l4'=>array('l5'=>'foo')))));
$a['l1']['l2']['l3']['l4']['l5'] = 'bar';
foreach ($a as $i => &$values) {
foreach ( $values as $key => &$value) {
if (is_array($value)){
print_array($value,$key);
}
}
}
function print_array ($Array, $parent) {
foreach ($Array as $i1 => &$values1) {
if (is_array($values1)){
foreach ($values1 as $key1 => &$value1) {
if (is_array($value1)) {
print_array($value1,$values1);
}
else {
print " $key1 => $value1\n";
}
}
}
else {
if (preg_match('/l5/',$i1)) {
$values1 = "foobar";
print " $i1 => $values1\n";
}
}
}
}
print_r($a);
Output does not reflect 'foobar' in l5
Because foreach operates on a copy of the array. Read the documentation about foreach:
Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.
So you should do
foreach ($array as $key => &$value) {
foreach ($value as $key2 => $value2) {
//...
}
}
Update:
Ok, I reviewed your code again:
Your code was not working as your loops never reach the array with key l5.
The code is highly inefficient. You make assumptions about the depth of the input array. E.g. your code cannot process the input array you provide (it should work if you omit one array).
Solution:
Make use of recursion. This code works:
$a =array('l1'=>array('l2'=>array('l3'=>array('l4'=>array('l5'=>'foo')))));
function process(&$array, $needle) {
foreach($array as $k => &$v) {
if ($k == $needle) {
$v = "boooooooooo";
print "$k => $v\n";
}
if (is_array($v)) {
process($v, $needle);
}
}
}
process($a, $needle);
print_r($a);
Hope that helps.
Oh and please use other keys next time. I thought the whole time that the key was 15 (fifteen) and was wondering why my example was not working ;) (15 looks not that different from l5 at a glance).
You have a few choices, but all stem from the same problem, which originates on this line
foreach ($array as $key => $value) {
At this point in the code, $value is not a reference to 2nd dimension of arrays in your data structure. To fix this, you have a couple options.
1) Force a reference
foreach ($array as $key => &$value) {
2) Use a "fully-qualified" expression to set the desired value
$array[$key][$key2] = 'bar';
Because $value is a new variable
Why not just:
foreach ($array as $key => &$value)
{
if(isset($value['slave']))
$value['slave'] = 'bar';
};

Iterating over a complex Associative Array in PHP

Is there an easy way to iterate over an associative array of this structure in PHP:
The array $searches has a numbered index, with between 4 and 5 associative parts. So I not only need to iterate over $searches[0] through $searches[n], but also $searches[0]["part0"] through $searches[n]["partn"]. The hard part is that different indexes have different numbers of parts (some might be missing one or two).
Thoughts on doing this in a way that's nice, neat, and understandable?
Nest two foreach loops:
foreach ($array as $i => $values) {
print "$i {\n";
foreach ($values as $key => $value) {
print " $key => $value\n";
}
print "}\n";
}
I know it's question necromancy, but iterating over Multidimensional arrays is easy with Spl Iterators
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($iterator as $key=>$value) {
echo $key.' -- '.$value.'<br />';
}
See
http://php.net/manual/en/spl.iterators.php
Looks like a good place for a recursive function, esp. if you'll have more than two levels of depth.
function doSomething(&$complex_array)
{
foreach ($complex_array as $n => $v)
{
if (is_array($v))
doSomething($v);
else
do whatever you want to do with a single node
}
}
You should be able to use a nested foreach statment
from the php manual
/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";
foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo "$v2\n";
}
}
Can you just loop over all of the "part[n]" items and use isset to see if they actually exist or not?
I'm really not sure what you mean here - surely a pair of foreach loops does what you need?
foreach($array as $id => $assoc)
{
foreach($assoc as $part => $data)
{
// code
}
}
Or do you need something recursive? I'd be able to help more with example data and a context in how you want the data returned.
Consider this multi dimentional array, I hope this function will help.
$n = array('customer' => array('address' => 'Kenmore street',
'phone' => '121223'),
'consumer' => 'wellington consumer',
'employee' => array('name' => array('fname' => 'finau', 'lname' => 'kaufusi'),
'age' => 32,
'nationality' => 'Tonga')
);
iterator($n);
function iterator($arr){
foreach($arr as $key => $val){
if(is_array($val))iterator($val);
echo '<p>key: '.$key.' | value: '.$val.'</p>';
//filter the $key and $val here and do what you want
}
}

Categories