John Davidson

arrays - PHP - iterate through different value types

0 comments
Message:


I have object of class $values like:


Array
(
[0] => App\ValueObject\Features Object
(
[feature:App\ValueObject\Features:private] => CONNECT_NETWORKS_ON_SIGN_UP
[value:App\ValueObject\Features:private] => 1
)

[1] => App\ValueObject\Features Object
(
[feature:App\ValueObject\Features:private] => SHOW_BILLING
[value:App\ValueObject\Features:private] => 1
)

[2] => App\ValueObject\Features Object
(
[feature:App\ValueObject\Features:private] => FEATURE_FLAGS
[value:App\ValueObject\Features:private] => 'activity'
)
)

All array keys are returning boolean type value expect one, which returns string value.


My result with the code:


$arrays = array_map(
function($value) { return [strtolower((string) $value->getFeature())]; },
iterator_to_array($values)
);
return array_merge(...$arrays);

returns list of feature names like:


"features": [
"connect_networks_on_sign_up",
"show_billing",
"feature_flags"
]

What I want to edit is that for the last one we write its value NOT feature name ($value->getValue())


I am assuming that using in_array() PHP function would be the best approach here but I can't find a way to use it within my current method.


Tried with foreach() loop but nothing happens, like it's something wrong:


    $features = [];
foreach ($values as $value)
{
$setParam = $value->getFeature();
if ($value == 'FEATURE_FLAGS') {
$setParam = $value->getValue();
}
$features[] = strtolower((string) $setParam);
}
return $features;

Can someone help?


Thanks



My Answer:
"string value",
[1] = 123,
[2] = true,
[3] = ["nested", "array"],
[4] = null
)

To iterate through the different value types in the array, you can use a foreach loop and check the type of each value using the `gettype()` function. Here's an example code snippet:

php
foreach ($values as $value) {
switch (gettype($value)) {
case 'string':
echo "String value: $value\n";
break;
case 'integer':
echo "Integer value: $value\n";
break;
case 'boolean':
echo "Boolean value: " . ($value ? 'true' : 'false') . "\n";
break;
case 'array':
echo "Array value:\n";
foreach ($value as $nestedValue) {
echo "- $nestedValue\n";
}
break;
case 'NULL':
echo "Null value\n";
break;
default:
echo "Unknown value type\n";
}
}


This code will iterate through each value in the array and print out the type of the value along with its actual value. You can customize the output as needed based on the value type.

Rate this post

4 of 5 based on 2259 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us