Push an array in to another array - php

I have an array like:
$profile_typeid [] = custom_profile(
0 => "44258",
1 => "44259",
);
and another array $meta_data[], I want to push this array $profile_typeid []. Before that it should check in $meta_data[] whether it contains $profile_typeid [] or not. If not then add other wise it should overwrite.
How can I get the things in PHP
I tried like:
if(!in_array($meta_data,$profile_typeid,true)){
array_push($meta_data, $profile_typeid);
}
I have var_dump for two arrays like
`array
'custom_profile_type' =>
array
0 => string '39242' (length=5)
null`

Change:
in_array($meta_data,$profile_typeid, true)
to
in_array($profile_typeid,$meta_data)
In your syntax you are searching for the haystack in the needle. (so to speak)
http://php.net/manual/en/function.in-array.php
Update:
To add in array use array_push.
if(!in_array($profile_typeid,$meta_data)){
array_push($meta_data, $profile_typeid);
}
else{
$meta_data['custom_profile_type'] = $profile_typeid;
}
Remove the strict clause. I do not think it is needed in this context.
This should work.

You can do it using below given code ...
$profile_typeid = array(
0 => "44258",
1 => "44259",
);
$meta_data = array(
0 => "34567",
1 => "67890",
2 => "44258"
);
foreach($profile_typeid as $pro_type){
if(!in_array($pro_type,$meta_data)){
array_push($meta_data, $pro_type);
}
}
print_r($meta_data);
The in_array(array(), $array, true); // false you are using which is totally wrong please check the manual for more details http://php.net/manual/en/function.in-array.php
Good luck with that ..

Related

How to see if an array of associative arrays is empty in php

I have a fairly easy issue where I need to see if an associative array of arrays is empty in php. My array looks like this:
array (
'person1' =>
array (
),
'person2' =>
array (
),
'person3' =>
array (
),
)
In my case, the three array's for the three people holds nothing so I need a test whether this is empty. I have done this which works:
if ( empty($form_values['person1']) && empty($form_values['person2']) && empty($form_values['person3'] ) ){
echo 'values empty!!';
}
But I was hoping something a bit more cleaner with using empty like the following:
if (empty( $form_values )) {
echo 'HI!';
}
You can use array_filter() to filter all of the empty array elements. You can then use empty to check if the result is empty then.
I've shorthanded the arrays so it's a easier to read since the arrays are empty. array() will work the same.
$form_values = [
'person1' => [],
'person2' => [],
'person3' => []
];
if (empty(array_filter($form_values))) {
// empty
} else {
// not empty
}
If you're looking for a one-liner then you could do something like:
$form_values = array (
'person1' =>
array (
),
'person2' =>
array (
),
'person3' =>
array (
),
);
if(array_sum(array_map(function($v){return !empty($v);}, $form_values)) === 0)
{
// empty
}
else
{
// not empty
}
Use a loop that tests each nested array. If none of them are non-empty, the whole array is empty.
$is_empty = true;
foreach ($form_values as $val) {
if (!empty($val)) {
$is_empty = false;
break;
}
}
<?php
$data =
[
'pig' => [],
'hog' => [],
'sow' => []
];
$all_empty = array_filter($data) === [];
var_dump($all_empty);
Output:
bool(true)
From the manual for array_filter:
If no callback is supplied, all empty entries of array will be
removed. See empty() for how PHP defines empty in this case.
Note that if an item was deemed as empty, like an empty string, it would still return true. This test may not be strict enough.
More explicitly:
if (array_filter($data, function($v) {return $v !== []; }) === []) {}
Filter out all items that aren't the empty array. What we'll be left with is an empty array if all items are an empty array.
Or search and compare:
if (array_keys($data, []) == array_keys($data)) {}
Check keys belonging to items containing the empty array match the keys of the array. Or rather all items (if they exist) are the empty array.
Note that an empty array will also satisfy the three solutions above.

Confusion with JSON_DECODE second param

I just created a small program to check JSON and JSON_FORCE_OBJECT
$tree = [
0 => array
(
'id' => 1,
'parent' => '0',
'name' => 'b',
'surname' => 'myfolder/b'
),
1 => array
(
'id' => 2,
'parent' => 1,
'name' => 'ignore',
'surname' => 'myfolder/ignore2'
),
2 => array
(
'id' => 3,
'parent' => 1,
'name' => 'ignore2',
'surname' => 'myfolder/ignore4'
)
];
var_dump($tree);
$try = json_encode($tree);//To print with key. Also if we decode we get result as object
//echo $try;
echo '<br />';
$try2 = json_decode($try,JSON_FORCE_OBJECT);
var_dump($try2);
$try2 is exactly equal to $tree an associative array.
Whereas if I remove JSON_FORCE_OBJECT from this line
$try2 = json_decode($try,JSON_FORCE_OBJECT);
I get an array with child object. Though JSON_FORCE_OBJECT is supposed to be used with json_encode but using it with json_decode, I get a surprising result. I am unable to understand whats going on inside?? I thought when I encode it and decode it I should get same result. But I got the same result only when I used JSON_FORCE_OBJECT. Can anyone please help why this happens?
According to the manual: http://php.net/manual/en/function.json-decode.php
json_decode returns an array of objects if you want to convert them in assoc array you should specify the second param which is a boolean
JSON_FORCE_OBJECT is an int with value 16...
when this is passed as second param php cast/converts it to its bool equivalent which true.
To test the above stated behavior try:
var_dump((bool)1; (bool)2, (bool)16)
//output bool(true) bool(true) bool(true) .
var_dump((bool)0)
//outputs bool(false)
So it's nothing to do with JSON_FORCE_OBJECT...even
json_decode($try,true);
json_decode($try,2);
json_decode($try,3);
json_decode($try,4);
json_decode($try,'someVar');
....
//should return your expected result (assoc array)
Similarly if you pass 0 as second param PHP will cast it into bool (which is false) and returns you an object
json_decode($try,0);
json_decode($try,false);
json_decode($try,null)
json_decode($try)
...
//will return objects
The second parameter to json_decode is a boolean. It accepts true or false. It does not accept JSON_FORCE_OBJECT. You're trying to use the wrong constant for the wrong function.
json_decode's 4th parameter accepts a bitmask of constants, but currently it only supports JSON_BIGINT_AS_STRING.
If you want to return stdClass instances for JSON objects from json_decode, set its second parameter to false (the default). Setting it to any non-falsey value makes it return associative arrays instead of objects. Setting it to JSON_FORCE_OBJECT counts as "not-falsey".
It's all described in the manual: http://php.net/json_decode

PHP Prepend two elements to associative array

I have the following array, I'm trying to append the following ("","--") code
Array
(
[0] => Array
(
[Name] => Antarctica
)
)
Current JSON output
[{"Name":"Antarctica"}]
Desired output
{"":"--","Name":"Antarctica"}]
I have tried using the following:
$queue = array("Name", "Antarctica");
array_unshift($queue, "", "==");
But its not returning correct value.
Thank you
You can prepend by adding the original array to an array containing the values you wish to prepend
$queue = array("Name" => "Antarctica");
$prepend = array("" => "--");
$queue = $prepend + $queue;
You should be aware though that for values with the same key, the prepended value will overwrite the original value.
The translation of PHP Array to JSON generates a dictionary unless the array has only numeric keys, contiguous, starting from 0.
So in this case you can try with
$queue = array( 0 => array( "Name" => "Antarctica" ) );
$queue[0][""] = "--";
print json_encode($queue);
If you want to reverse the order of the elements (which is not really needed, since dictionaries are associative and unordered - any code relying on their being ordered in some specific way is potentially broken), you can use a sort function on $queue[0], or you can build a different array:
$newqueue = array(array("" => "--"));
$newqueue[0] += $queue[0];
which is equivalent to
$newqueue = array(array_merge(array("" => "--"), $queue[0]));
This last approach can be useful if you need to merge large arrays. The first approach is probably best if you need to only fine tune an array. But I haven't ran any performance tests.
Try this:
$queue = array(array("Name" => "Antarctica")); // Makes it multidimensional
array_unshift($queue, array("" => "--"));
Edit
Oops, just noticed OP wanted a Prepend, not an Append. His syntax was right, but we was missing the array("" => "--") in his unshift.
You can try this :
$queue = array("Name" => "Antarctica");
$result = array_merge(array("" => "=="), $queue);
var_dump(array_merge(array(""=>"--"), $arr));

Accessing an array inside of an array

When trying to access an array inside an array, only NULL is output.
My Code:
$aStats = array();
$aStats['hd'] = array();
$aStats['hd'][] = array
(
'dev' => $device,
'total' => $total,
'used' => $used,
'free' => $free,
'used_perc' => $used_perc,
'mount' => $folder
);
echo $aStats['hd']['free'];
When using json_encode, the values are displayed correctly:
die( json_encode( $aStats ) );
Where is my mistake?
Replace these lines:
$aStats['hd'] = array();
$aStats['hd'][] = array
With this:
$aStats['hd'] = array
You appear to be accessing your array ($aStats['hd']['free'];) as if the value of hd is an associated array, but using [] creates a new integer index in the array, and stores the value in that index. Joe Walker's answer shows what happens instead, that you have an associative array pointing to an indexed array pointing to another associative array, rather than the associative to associative array you suggest you're trying to use in your echo statement.
This is a practical tip that will let you find out where is the issue easly, all you need to do is:
var_dump($aStats);
This will output:
array (size=1)
'hd' =>
array (size=1)
0 =>
array (size=6)
'dev' => string 'SomeDevice' (length=10)
'total' => string '10000' (length=5)
'used' => boolean true
'free' => boolean false
'used_perc' => string 'none' (length=4)
'mount' => string '/some/directory/here/' (length=21)
Now you know you can access this element using
$aStats['hd'][0]['free'];
This will return null in your question because your variables are not yet initialized, but I guess you do have them initialized in your code, hope this helps.

Percentages in key of an array

I'm currently reading through some code in a drupal module and have come across the following in an associative array.
$this->replacements = array(
'%field' => $this->instance['label'],
'%bundle' => $bundles[$this->instance['entity_type']][$this->instance['bundle']]['label'],
);
What does the % in the key mean or is it just a string label
I think its just sting label.
$a = array("%name" => "pugazh", "vaalue" => "value");
print_r($a);
If you try like this in corephp it will return an output like this
Array ( [%name] => pugazh [vaalue] => value )
But i don't know what its mean in drupal.

Categories