PHP if statement inside an array - php

I'm trying to write the below array if a value is set. How can I do this inside of an array? I know I could use a ternary operator but i'm not sure how.
array(
'name' => 'extraFields',
'attributes' => array(
'name' => 'portal',
),
if($Value === 1){
//Need to write the below when value is true
array(
'name' => 'portal',
'value'=> '',
'attributes' => array(
'id' => '1',
'value'=> 'testportal',
),
),
}
),

You cannot intersect a definition of an array with a conditional statement. What you need to do instead is to define your array first and then do an if statement which will add to the array. It's not entirely clear at what level of your array you want to add the conditional content, so I'll show it on a simplified example:
$value = 1;
$myArray = array(
'name' => 'Joe',
'kids' => array(
'name' => 'Mary',
),
);
if ($value === 1) {
$myArray['kids']['hobbies'] = 'kite flying';
}
After this, the variable $myArray will have the following content:
array(
'name' => 'Joe',
'kids' => array(
'name' => 'Mary',
'hobbies' => 'kite flying',
),
)
Where exactly you need to put your conditional data depends on the full structure of your array, but the idea is you access the parts you want through indices.
Edit: in case you can just add the needed subarray at the end of your array, you can utilize array_push.

There is 3 variants to do this:
// Variant 1
// Anonymous function, variables from the parent scope
$Value = 1;
$arr = array(
'name' => 'extraFields',
'attributes' => array(
'name' => 'portal',
),
'ifArray' => function() use ($Value) {
if ($Value == 1)
return array(
'name' => 'portal',
'value'=> '',
'attributes' => array(
'id' => '1',
'value'=> 'testportal',
),
);
}
);
print_r($arr['ifArray']());
// Variant 2
// Anonymous function, variable assignment
$arr = array(
'name' => 'extraFields',
'attributes' => array(
'name' => 'portal',
),
'ifArray' => function($Value) {
if ($Value == 1)
return array(
'name' => 'portal',
'value'=> '',
'attributes' => array(
'id' => '1',
'value'=> 'testportal',
),
);
}
);
$Value = 1;
print_r($arr['ifArray']($Value));
// Variant 3
// Ternar operator
$Value = 1;
$arr = array(
'name' => 'extraFields',
'attributes' => array(
'name' => 'portal',
),
'ifArray' => $Value != 1 ? null : array(
'name' => 'portal',
'value'=> '',
'attributes' => array(
'id' => '1',
'value'=> 'testportal',
)
)
);
print_r($arr['ifArray']);
However, the variant that El_Vanja suggested, might be more clear than those three.

Related

Replace key in array, with keeping order intact

I would like to replace keys in arrays, because I will move them on two indexes up.
Problem that I am facing is that those are containing same names which will not be ok, if i want to move them up.
This is how array looks like.
$list = array(
'ind' => array(
'messagetype' => 'Alert',
'visibility' => 'Public',
'info' => array(
0 => array(
'urgency' => 'Urgent',
'params' => array(
0 => array(
'Name' => 'display',
'value' => '3; top',
),
1 => array(
'Name' => 'level',
'value' => '1; blue',
),
),
'area' => array(
'ard' => 'Bob',
'code' => array(
0 => array(
'Name' => 'Badge',
'value' => 'GSSD154',
),
),
),
),
1 => array(
'messagetype' => 'Information',
'visibility' => 'Private',
'info' => array(
0 => array(
'urgency' => 'Minor',
'params' => array(
0 => array(
'Name' => 'display',
'value' => '1; left',
),
1 => array(
'Name' => 'level',
'value' => '1; red',
),
),
'area' => array(
'ard' => 'Bob',
'code' => array(
0 => array(
'Name' => 'Badge',
'value' => 'GBECS23',
),
),
),
),
),
),
),
),
);
and this is how I would like the output to be with changing keys in Name0, Name1, which are inside params.
$list = array(
'ind' => array(
'messagetype' => 'Alert',
'visibility' => 'Public',
'info' => array(
0 => array(
'urgency' => 'Urgent',
'params' => array(
0 => array(
'Name0' => 'display',
'value0' => '3; top',
),
1 => array(
'Name1' => 'level',
'value1' => '1; blue',
),
),
'area' => array(
'ard' => 'Bob',
'code' => array(
0 => array(
'Name' => 'Badge',
'value' => 'GSSD154',
),
),
),
),
1 => array(
'messagetype' => 'Information',
'visibility' => 'Private',
'info' => array(
0 => array(
'urgency' => 'Minor',
'params' => array(
0 => array(
'Name0' => 'display',
'value0' => '1; left',
),
1 => array(
'Name1' => 'level',
'value1' => '1; red',
),
),
'area' => array(
'ard' => 'Bob',
'code' => array(
0 => array(
'Name' => 'Badge',
'value' => 'GBECS23',
),
),
),
),
),
),
),
),
);
I have tried with a lots of examples over this website, but could not find one to achieve this.
Code that I used from
How to replace key in multidimensional array and maintain order
function replaceKey($subject, $newKey, $oldKey) {
// if the value is not an array, then you have reached the deepest
// point of the branch, so return the value
if (!is_array($subject)) {
return $subject;
}
$newArray = array(); // empty array to hold copy of subject
foreach ($subject as $key => $value) {
// replace the key with the new key only if it is the old key
$key = ($key === $oldKey) ? $newKey : $key;
// add the value with the recursive call
$newArray[$key] = replaceKey($value, $newKey, $oldKey);
}
return $newArray;
}
$s = replaceKey($list, 'Name0', 'Name');
print "<PRE>";
print_r($s);
at the moment I get this output:
[0] => Array
(
[Name0] => display
[value] => 1; left
)
[1] => Array
(
[Name0] => level
[value] => 1; red
)
any help would be appreciated. regards
A very strange question, but why not?
The following function returns nothing (a procedure) and changes the array in-place using references but feel free to rewrite it as a "real" function (without references and with a return statement somewhere).
The idea consists to search for arrays, with numeric keys and at least 2 items, in which each item has the Name and value keys. In other words, this approach doesn't care about paths where the targets are supposed to be:
function replaceKeys(&$arr) {
foreach ($arr as &$v) {
if ( !is_array($v) )
continue;
$keys = array_keys($v);
if ( count($keys) < 2 ||
$keys !== array_flip($keys) ||
array_keys(array_merge(...$v)) !== ['Name', 'value'] ) {
replaceKeys($v);
continue;
}
foreach ($v as $k => &$item) {
$item = array_combine(["Name$k", "value$k"], $item);
}
}
}
replaceKeys($list);
print_r($list);
demo

Recursive replace one array with specific key with another arrays

I have an array where all arrays where key type == 'foo' must be replaced by a custom arrays.
Basically I need to find a specific array and then replace it with other arrays.
The issue here you can easily replace one array but when you insert numbers of arrays you are shifting keys so the next array type == 'foo' will not be replaced
Any help would be appreciated.
Here's what I have:
$array = array(
array(
'options' => array(
array(
'type' => 'foo'
),
array(
'type' => 'foo'
),
array(
'type' => 'bar'
)
)
),
array(
'options' => array(
array(
'type' => 'bar'
),
array(
'type' => 'bar'
),
array(
'type' => 'foo'
)
)
),
);
And I have an array which should replace any array where type == 'foo'
$array_foo = array(
array(
'type' => 'custom'
),
array(
'type' => 'custom_2'
),
array(
'type' => 'anything'
),
);
Here is the desired output:
$array = array(
array(
'options' => array(
array(
'type' => 'custom'
),
array(
'type' => 'custom_2'
),
array(
'type' => 'anything'
),
array(
'type' => 'custom'
),
array(
'type' => 'custom_2'
),
array(
'type' => 'anything'
),
array(
'type' => 'bar'
)
)
),
array(
'options' => array(
array(
'type' => 'bar'
),
array(
'type' => 'bar'
),
array(
'type' => 'custom'
),
array(
'type' => 'custom_2'
),
array(
'type' => 'anything'
),
)
),
);
Thank you.
Here's a way using 2 nested foreach loops and array_merge() with a temporary array:
// Pass the array by reference
foreach ($array as &$sub) {
// Temporary array
$new_options = [];
// Loop through options
foreach ($sub['options'] as $opt) {
// if type foo: replace by $array_foo items
if ($opt['type'] == 'foo') {
$new_options = array_merge($new_options, $array_foo);
// else, keep original item
} else {
$new_options[] = $opt;
}
}
// replace the options
$sub['options'] = $new_options;
}
And check the output:
echo '<pre>' . print_r($array, true) . '</pre>';
See also Passing by Reference
According to a previous post, the code for changing could be done in a similar fashion to the following code:
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");
$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);
So with your method instead of having numbers or indexes, I think you might be able to get away with writing down foo instead to get the replacement to work properly.
The other thing you might look into is array merge-recursive which can be found at: http://php.net/array_merge_recursive
The problem you stated here looks similar to this post: PHP Array Merge two Arrays on same key
I hope this helps you.

Using array_search for multi value search

$array_subjected_to_search =array(
array(
'name' => 'flash',
'type' => 'hero'
),
array(
'name' => 'zoom',
'type' => 'villian'
),
array(
'name' => 'snart',
'type' => 'antihero'
),
array(
'name' => 'flash',
'type' => 'camera'
)
);
$key = array_search('flash', array_column($array_subjected_to_search, 'name'));
var_dump($array_subjected_to_search[$key]);
This works fine, but is there a way to search using multiple values: eg. get key where name='flash' && type='camera' ?
is there a way to search using multiple values: eg. get key where
name='flash' && type='camera' ?
Simply with array_keys function:
$result_key = array_keys($array_subjected_to_search, [ 'type' => 'camera','name' => 'flash']);
print_r($result_key);
The output:
Array
(
[0] => 3
)
The array_search function accepts an array as parameters the following will work for the use case you provided.
$array_subjected_to_search =array(
array(
'name' => 'flash',
'type' => 'hero'
),
array(
'name' => 'zoom',
'type' => 'villian'
),
array(
'name' => 'snart',
'type' => 'antihero'
),
array(
'name' => 'flash',
'type' => 'camera'
)
);
$compare = array(
'name'=>'flash',
'type'=>'camera'
);
$key = array_search($compare, $haystack);
var_dump($haystack[$key]);
Note: your current search will not function correctly it will always return the zero index because the array_search returns 0 or false.
$key = array_search('flash', array_column($array_subjected_to_search, 'name'));
var_dump($array_subjected_to_search[$key]);
I think I would just make my own function using a loop that will just retrieve the array I want based on either one or two parameters.
function getValueMatch($array, $val1, $val2 = false, $type = 'name')
{
foreach($array as $key => $row) {
# See note below, but it might be handy to have a reversible key name
if($row[$type] == $val1) {
if($val2) {
# You can put a changeable key name to reverse-find
# It might be helpful to search for the other key first
# at some point, best to keep your options open!
$altVar = ($type == 'name')? 'type' : 'name';
if($row[$altVar] == $val2)
return $row;
}
else
return $row;
}
}
}
$array =array(
array(
'name' => 'flash',
'type' => 'hero'
),
array(
'name' => 'zoom',
'type' => 'villian'
),
array(
'name' => 'snart',
'type' => 'antihero'
),
array(
'name' => 'flash',
'type' => 'camera'
)
);
print_r(getValueMatch($array,'flash','camera'));
Gives you:
Array
(
[name] => flash
[type] => camera
)
Example of reverse match (type instead of name):
print_r(getValueMatch($array,'antihero',false,'type'));
Gives you:
Array
(
[name] => snart
[type] => antihero
)

PHP: how to get array based on nested value

Given this array and a name (e.g. 'def'), how do I get the containing array, or key?
$all = array(
'0' => array(
'name' => 'abc'
'option' => 1,
),
'1' => array(
'name' => 'def'
'option' => 1,
),
'2' => array(
'name' => 'ghi'
'option' => 0,
),
);
What's the best way to return this array given 'def'?
$single = array(
'name' => 'def'
'option' => 1,
);
I could do something like this:
$single = array();
foreach ($all as $key => $value) {
if ($value['name'] == 'def') {
$single = $all[$key];
}
}
Or prerender the keys in the array so that it looks like this:
$all = array(
'abc' => array(
'name' => 'abc'
'option' => 1,
),
'def' => array(
'name' => 'def'
'option' => 1,
),
'ghi' => array(
'name' => 'ghi'
'option' => 0,
),
);
$single = $all['def'];
But I'm wondering if there's a shorter php function for that.
You could use array_filter:
array_filter($array, function($var){
return $var["name"] == "def";
});

Multidimensional array and array_push?

I have a huge multidimensional array, let's name it $big_array.
In addition I have this set of data that I have to put into above array:
$input = array('one','two','three','four');
That's what I need to push into $big_array (based on $input from above):
$value = array(
'id' => $number,
'title' => 'foo',
'type' => 'options',
'options' => array('one','two','three','four'),
'page' => 'font_manager',
);
array_push($big_array, $value);
$big_array structure looks like this:
$big_array = array(
(...)
array(
'id' => 'Bar',
'title' => 'Foo',
'type' => 'select',
'page' => 'font_manager',
),
array(
'id' => 'ss_font',
'title' => __("Main font:",'solidstyle_admin'),
'type' => 'select',
'page' => 'font_manager',
'description' => __("This font will be used for all pages.",'solidstyle_admin'),
'default' => '',
'options' => array(
'option1' => 'option1',
'option2' => 'option12,
),
),
(...)
);
What I exactly want to do will look like that if it will be possible to include loops in arrays (yes, I know how wrong is that, just trying to explain it better):
$input = array('one','two','three','four');
$value = array(
'id' => $number,
'title' => 'foo',
'type' => 'options',
'options' => array(
foreach($input as $number) {
echo $number.',';
};
),
'page' => 'font_manager',
);
I think what you are going for is getting
$input = array('one','two','three','four');
inserted into
$value = array(
'id' => $number,
'title' => 'foo',
'type' => 'options',
'page' => 'font_manager',
);
so that it looks like this:
$value = array(
'id' => $number,
'title' => 'foo',
'type' => 'options',
'options' => array('one','two','three','four'),
'page' => 'font_manager',
);
and can then be pushed onto $bigArray . If that is the case, it should be as simple as
$input = array('one','two','three','four');
$value = array(
'id' => $number,
'title' => 'foo',
'type' => 'options',
'page' => 'font_manager',
);
$value['options'] = $input;
$bigArray[] = $value; // equivalent to array_push($bigArray, $value);
If I misunderstood your goal, please let me know.
edit: If you are going for something like this
$value = array(
'id' => $number,
'title' => 'foo',
'type' => 'options',
'options' => array('one,two,three,four'),
'page' => 'font_manager',
);
then it you would just change
$value['options'] = $input;
to
$value['options'] = implode(",",$input);
Have a look at the code below. I have commented it so you can understand what I'm doing.
$input = array('one','two','three','four');
// set the base info here, i.e., info that is common to each push
$baseInfo = array(
'title' => 'foo',
'type' => 'options',
'page' => 'font_manager',
);
// now loop
foreach($input as $number) {
// fill in base info with data that is specific to this iteration
$baseInfo['id'] = $number;
$baseInfo['options'] = $input;
// do the push
array_push($big_array, $baseInfo);
}
I'm not entirely sure I got your question correct. If you were asking something else, please clarify and I will edit my answer.
There are a few ways you could emulate the foreach loop at $array['options']— the simplest would be to define a function elsewhere that does that, and then return that options array! Like:
function return_array_options($input) {
$array = array();
foreach($input as $number) {
$array[] = $number
// or, $array['option'.$number] = $number
};
return $array;
}
Then elsewhere in your code you can use this function:
$my_array = array();
$my_array['options'] = return_array_options(array(1,2,3,4));
With programming, it's always better to break things down into solutions to smaller problems that you then combine.
Also, check out PHP's functional programming functions, like array_map(), and array_filter(). They help to transform things just like a loop woud, but without actually using a loop. So, they are syntatically more flexible in some ways.
If i understand well. You wish to get this :
$input = array('one','two','three','four');
$value = array(
'id' => $number,
'title' => 'foo',
'type' => 'options',
'options' => array(
foreach($input as $number) {
echo $number.',';
};
),
'page' => 'font_manager',
);
And to push it into $big_array, am i right ?
Then the solution is pretty simple.
$input = array('one','two','three','four');
$value = array(
'id' => $number,
'title' => 'foo',
'type' => 'options',
'options' => array(
),
'page' => 'font_manager',
);
Build your array. Then your loop :
foreach($input as $number)
{
$value['options'][] = $number;
}
If you wan to add $input "as is", you may do
$value['options'] = $input;
If you want to have 'one' => 'one'
foreach($input as $number)
{
$value['options'][$number] = $number;
}
It will produce the exact same result than a loop, withouth the loop overhead.
And finally :
array_push($big_array, $value);

Categories