I can't compare associative array indexes to a var - php

I can not figure out how to compare the array index. I know this has to be simple.
$list_array array (
'first' => array('one' => 1, 'two' => 2),
'second' => array('one' => 3, 'two' => 4)
);
foreach ($list_array as $key) {
if(<the-list_array-index> == 'second' ) {
echo $key['one']. ' - '. $key['two'];
}
}
result 3 - 4

Use this syntax:
foreach ($array as $key => $value)
foreach ($list_array as $index => $key) {
if($index == 'second' ) {
echo $key['one']. ' - '. $key['two'];
}
}
One suggestion though: Rename $key to an appropriate and meaningful name in your context!
If you do not find any or if your function works with arrays in general, use $value since this term is very well-known among developers:
foreach ($list_array as $index => $value) {
if($index == 'second') {
echo $value['one'] . ' - ' . $value['two'];
}
}
Consider u_mulder's answer below if you just want to directly access the key. As far as I can see in your code, a loop is unnecessary.

if (array_key_exists('second', $list_array))
echo $list_array['second']['one'] . ' - ' . $list_array['second']['two'];

Related

Is there a better solution than this to print the results

<?php
$arr =
[
'name' => 'hussin' ,
"age" => 25,
'job' =>
[
'php', 'ajax'
]
];
foreach ($arr as $key => $value)
{
if(!is_array($arr[$key]))
echo $key .' '. $value."<br>";
else
foreach ($arr['job'] as $key => $value)
echo $key .' '. $value."<br>";
}
?>
result
name Hussien
age 27
0 php
1 ajax
Is there a better solution than this to print the results?
I have an associative array with regular data, including a array type, which is the best solution for accessing all data
I may be misunderstanding, but I think you're looking for a recursive algorithm:
function printAll(array $arr){
foreach($arr as $k => $v){
if(is_array($v)){
return printAll($v);
}
print $k . ":" . $v . "\r\n";
}
}
printAll(['name' => 'hussin' ,"age" => 25,'job' => ['php', 'ajax']]); // name:hussin age:25 0:php 1:ajax
Now, this can of course be improved to deal with other iterables and the nested array keys, but hopefully you get the jist.

How do I reduce this function into a recursive one?

I have a function that returns an array with empty keys from the input array. The problem is that I've been working on an inconsistent data. The data could go to any level of nested array. For example,
$inputArray = [
'a' => 'value a',
'b' => [
1 => [],
2 => 'value b2',
3 => [
'x' => 'value x'
'y' => ''
],
'c' => ''
],
];
I need an output that converts this kind of data to string. So,
$outputArray = [
'empty' => [
'b[1]',
'b[3][y]',
'c'
]
];
Here's what I have so far to get keys with empty values:
$outputArray = [];
foreach ($inputArray as $key => $value) {
if (is_array($value)) {
foreach ($value as $index => $field) {
if (is_array($field)) {
foreach ($field as $index1 => $value1) {
if (empty($value1)) {
array_push($outputArray['empty'], $key . '[' . $index . ']' . '[' . $index1 . ']');
}
}
}
if (empty($field)) {
array_push($outputArray['empty'], $key . '[' . $index . ']');
}
}
}
if (empty($value)) {
array_push($outputArray['empty'], $key);
}
}
return $outputArray;
As I said the input array could be nested to any level. I cannot keep on adding if (is_array) block every time the array is nested one more level. I believe it could be solved using a recursive function, but I cannot seem to figure out how. Please help me with this. Thanks.
You are right about a recursive function but you should also be aware of recursions, whether we are in or out of a recursion. The tricky part is passing current level keys to the recursive function:
function findEmpties($input, $currentLevel = null) {
static $empties = [];
foreach ($input as $key => $value) {
$levelItem = $currentLevel ? "{$currentLevel}[{$key}]" : $key;
if (empty($value)) {
$empties['empty'][] = $levelItem;
} else {
if (is_array($value)) {
findEmpties($value, $levelItem);
}
}
}
return $empties;
}
Live demo

How to make a associative array from other associative array?

I need some help with another PHP problem I am working on. I won't be posting the exact question, as I'd prefer to try and apply the knowledge I get from here to solve my problem.
First:
I have an associative array. I must loop through the array to find the array values which have keys that begin with a specific string and push both the key and value to an output array.
eg:
- Loop through the below array & push all elements which have a key beginning with "edible_" to an output array:
$assoc_array = array(
'edible_fruit' => 'apple',
'animal' => 'cat',
'edible_veg' => 'pumpkin',
'number' => '23',
'city' => 'Cape Town',
'edible_berry' => 'blueberry',
'color' => 'blue'
);
Would this work?
$result = array();
foreach ($assoc_array as $key => $value) {
if (substr($key, 0, 7) == "edible_") {
array_push($result, $value);
}
}
print_r($result);
Second:
How would I remove "edible_" from the output array's keys? With this second bit I have no idea where to even begin!
Third:
I've managed to figure out the above with all your help, thank you! Now I just need to find out how I would print each element on a new line with a date & timestamp at the end of each line? I've got this (doesn't seem to be working):
while (list($key, $value) = each($output)) {
print_r("$key => $value" . date("y/m/d G.i:s", time()) . "<br>");
}
First of your code will work.
To remove edible_ from the key you could use explode() -
$keyParts = explode('_', $key);
$newKey = $keyParts[1];
You will have to add the new keys to the array, which you're not doing now.
foreach ($assoc_array as $key => $value) {
if (substr($key, 0, 7) == "edible_") {
$keyParts = explode('_', $key);
$newKey = $keyParts[1];
$result[$newKey] = $value;
}
}
This would be my approach:
foreach($assoc_array as $key => $value) {
if(preg_match("/^edible_/",$key)) {
$result[preg_replace("/^edible_/","",$key)] = $value;
}
}
use preg_match to check if the key starts with what you are looking for and use preg_replace to remove the string from the beginning (^) of the key :)
Input ($assoc_array):
Array
(
[edible_fruit] => apple
[animal] => cat
[edible_veg] => pumpkin
[number] => 23
[city] => Cape Town
[edible_berry] => blueberry
[color] => blue
)
Output ($result):
Array
(
[fruit] => apple
[veg] => pumpkin
[berry] => blueberry
)
First: yes, that would work, however I would rewrite it a bit:
foreach ($assoc_array as $key => $value) {
if (strpos($key, 'edible_') === 0) {
$result[] = $value;
}
}
Regarding Second: You are asking how to remove the key from the output array. However you did not even push the key into the output array, you only pushed the value. If you'd like to also push the key, you should do it like this:
$result[$key] = $value;
But since you haven't done that, there's no need to remove the key.
If you however meant removing the edible_ part of the key from the $assoc_array, you'd just need to add a line to the loop and pass the key by reference by adding a &:
foreach ($assoc_array as &$key => $value) {
if (strpos($key, 'edible_') === 0) {
$key = str_replace('edible_', '', $key)
$result[] = $value;
}
}
Edit: As OP told me in comments, she wants to push the key without the edible part. So just do it like this:
foreach ($assoc_array as $key => $value) {
if (strpos($key, 'edible_') === 0) {
$key = str_replace('edible_', '', $key)
$result[$key] = $value;
}
}
This should work for you:
First I remove all elements, which doesn't have edible_ at the start of the key with array_diff_ukey(). After this I simply array_combine() the elements with they keys, where I remove the prefix with array_map() and substr().
<?php
$assoc_array = array('edible_fruit'=>'apple', 'animal'=>'cat', 'edible_veg'=>'pumpkin', 'number'=>'23', 'city'=>'Cape Town', 'edible_berry'=>'blueberry', 'color'=>'blue');
//remove elemnts
$result = array_diff_ukey($assoc_array, ["edible_" => ""], function($k1, $k2){
return substr($k1, 0, 7) == $k2;
});
//change keys
$result = array_combine(
array_map(function($v){
return substr($v, 7);
}, array_keys($result)),
$result);
print_r($result);
?>
output:
Array ( [fruit] => apple [veg] => pumpkin [berry] => blueberry )
You can loop through the array and search if the key has the string that you can eliminate and make your $newArray
<?php
$assoc_array = array('edible_fruit'=>'apple', 'animal'=>'cat', 'edible_veg'=>'pumpkin', 'number'=>'23', 'city'=>'Cape Town', 'edible_berry'=>'blueberry', 'color'=>'blue');
$search = 'edible_';
$newArray = array();
#First and Second Step
foreach($assoc_array as $key => $value) {
if(strpos($key, "edible_") === 0) {
$newArray[substr($key, 7)] = $value;
}
}
print_r($newArray);
echo "<br>\n";
#Third Step
foreach($newArray as $key => $value) {
echo "$key => $value " . date("y/m/d G.i:s", time()) . "<br>\n";
}
Output:
#First and Second Step
Array ( [fruit] => apple [veg] => pumpkin [berry] => blueberry )
#Third Step
fruit => apple 15/04/10 3.02:16
veg => pumpkin 15/04/10 3.02:16
berry => blueberry 15/04/10 3.02:16

PHP: Get key from array?

I am sure that this is super easy and built-in function in PHP, but I have yet not seen it.
Here's what I am doing for the moment:
foreach($array as $key => $value) {
echo $key; // Would output "subkey" in the example array
print_r($value);
}
Could I do something like the following instead and thereby save myself from writing "$key => $value" in every foreach loop? (psuedocode)
foreach($array as $subarray) {
echo arrayKey($subarray); // Will output the same as "echo $key" in the former example ("subkey"
print_r($value);
}
Thanks!
The array:
Array
(
[subKey] => Array
(
[value] => myvalue
)
)
You can use key():
<?php
$array = array(
"one" => 1,
"two" => 2,
"three" => 3,
"four" => 4
);
while($element = current($array)) {
echo key($array)."\n";
next($array);
}
?>
Use the array_search function.
Example from php.net
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
$foo = array('a' => 'apple', 'b' => 'ball', 'c' => 'coke');
foreach($foo as $key => $item) {
echo $item.' is begin with ('.$key.')';
}
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
If it IS a foreach loop as you have described in the question, using $key => $value is fast and efficient.
If you want to be in a foreach loop, then foreach($array as $key => $value) is definitely the recommended approach. Take advantage of simple syntax when a language offers it.
Another way to use key($array) in a foreach loop is by using next($array) at the end of the loop, just make sure each iteration calls the next() function (in case you have complex branching inside the loop)
Try this
foreach(array_keys($array) as $nmkey)
{
echo $nmkey;
}
Here is a generic solution that you can add to your Array library. All you need to do is supply the associated value and the target array!
PHP Manual: array_search() (similiar to .indexOf() in other languages)
public function getKey(string $value, array $target)
{
$key = array_search($value, $target);
if ($key === null) {
throw new InvalidArgumentException("Invalid arguments provided. Check inputs. Must be a (1) a string and (2) an array.");
}
if ($key === false) {
throw new DomainException("The search value does not exists in the target array.");
}
return $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

Categories