Adding new values to start of an array in PHP [duplicate] - php

This question already has answers here:
How to insert an item at the beginning of an array in PHP?
(8 answers)
Closed 1 year ago.
I tried with array_push(), but I get fatal error.
function get_data($table, $id = '', $condition){
if($id != '')
array_push( " WHERE `id` = '".$id."' ", $condition );
...
}
The question is, how to add a value (in my case a string) to the start of an array?

array_unshift() is the function you are looking for!
array_unshift — Prepend one or more elements to the beginning of an array
$arr = array(1,2,3);
print_r($arr);
/*
Array
(
[0] => 1
[1] => 2
[2] => 3
)
*/
array_unshift($arr,0);
print_r($arr);
/*
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)
*/

The fatal error is because you have the arguments in reverse order:
function get_data($table, $id = '', $condition){
if($id != '')
array_push($condition, " WHERE `id` = '".$id."' " );
...
}
if $condition is an array, this will not give a fatal error, but it will place the item at the end of the array. As mentioned in other answers, array_unshift is the function to prepend an item.

array_unshift should do the trick

Related

How to calculate difference between keys and values in php [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I have two types of arrays:
1:
$array1["a"][] = "value1";
$array1["a"][] = "value2";
$array1["b"][] = "value3";
2:
$array2["0"] = "a";
What I need now is to somehow find difference between these two arrays. I need to filter out array1 by key, which is located in array2 value. I have tried doing the following:
array_diff(array_keys($array1), array_values($array2));
But I get the following error on that line:
ErrorException Array to string conversion
Any ideas?
Something like this?
foreach ($array1 as $key => $value)
if( array_search ($key , $array2 ))
unset($array1[$key]);
If $array1 needs to have the values, you just need to put the diff in $array1 :
$array1 = array_diff(array_keys($array1), array_values($array2));
Depending on how you constructed your arrays, it should work. The following code (based on your question) worked:
<?php
$array1=array("a" => array(),"a" => array(),"b" => array());
$array2=array("0"=>"a");
print_r(array_keys($array1));
echo("<br/>");
print_r(array_values($array2));
echo("<br/>");
print_r(array_diff(array_keys($array1), array_values($array2)));
>
This results in:
Array ( [0] => a [1] => b )
Array ( [0] => a )
Array ( [1] => b )

Parsing complex json object in PHP [duplicate]

This question already has answers here:
Get value without knowing key in one-pair-associative-array
(4 answers)
Closed 5 years ago.
i have this scenario of having a mixed response from a server and i need to process its data in PHP
Array
(
[14424174] => Array
(
[0] => Array
(
[id] => 45
[nm] => This is a driver name
[ph] => 5454545
)
)
)
I want to access id, nm, ph values
but i had no luck cause this index number (14424174) is unknown to me, so i need to first store this index and then parse the array
Use a nested foreach():
foreach($arr as $i => $sub_arr)
{
foreach($sub_arr as $sub_i => $sub_sub_arr)
{
$id = $sub_sub_arr['id'];
$nm = $sub_sub_arr['nm'];
$ph = $sub_sub_arr['ph'];
}
}
You can use the following pattern:
foreach($array as $key=>$val) {
//get the id:
var_dump($key)//14424174
$nm = $val[nm];
$ph = $val[ph];
}

remove same values from an array [duplicate]

This question already has answers here:
Remove duplicates from Array
(2 answers)
Closed 9 years ago.
I have an array like this
Array
(
[0] => u1,u2
[1] => u2,u1
[2] => u4,u3
[3] => u1,u3
[4] => u1,u2
)
I want to remove similar values from the array
I want an out put like
Array
(
[0] => u1,u2
[1] => u4,u3
[2] => u1,u3
)
I tried to loop thru the input array, sort the value of the indexes alphabetically and then tried array_search to find the repeated values. but never really got the desired output
any help apprecated
You cannot use array_unique() alone, since this will only match exact duplicates only. As a result, you'll have to loop over and check each permutation of that value.
You can use array_unique() to begin with, and then loop over:
$myArray = array('u1,u2', 'u2,u1', 'u4,u3', 'u1,u3', 'u1,u2');
$newArr = array_unique($myArray);
$holderArr = array();
foreach($newArr as $val)
{
$parts = explode(',', $val);
$part1 = $parts[0].','.$parts[1];
$part2 = $parts[1].','.$parts[0];
if(!in_array($part1, $holderArr) && !in_array($part2, $holderArr))
{
$holderArr[] = $val;
}
}
$newArr = $holderArr;
The above code will produce the following output:
Array (
[0] => u1,u2
[1] => u4,u3
[2] => u1,u3
)
Use array_unique() PHP function:
http://php.net/manual/en/function.array-unique.php
Use the function array_unique($array)
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
php manual
since u1,u2 !== u2,u1
$array=array('u1,u2','u2,u1','u4,u3','u1,u3','u1,u2');
foreach($array as $k=>$v)
{
$sub_arr = explode(',',$v);
asort($sub_arr);
$array[$k] = implode(',',$sub_arr);
}
$unique_array = array_unique($array);
//$unique_array = array_values($unique_array) //if you want to preserve the ordered keys

PHP: remove empty array strings in multidimensional array [duplicate]

This question already has answers here:
How to remove empty values from multidimensional array in PHP?
(9 answers)
Closed 9 years ago.
I have this array:
$aryMain = array(array('hello','bye'), array('',''),array('',''));
It is formed by reading a csv file and the array('','') are the empty rows at the end of the file.
How can I remove them?
I've tried:
$aryMain = array_filter($aryMain);
But it is not working :(
Thanks a lot!
To add to Rikesh's answer:
<?php
$aryMain = array(array('hello','bye'), array('',''),array('',''));
$aryMain = array_filter(array_map('array_filter', $aryMain));
print_r($aryMain);
?>
Sticking his code into another array_filter will get rid of the entire arrays themselves.
Array
(
[0] => Array
(
[0] => hello
[1] => bye
)
)
Compared to:
$aryMain = array_map('array_filter', $aryMain);
Array
(
[0] => Array
(
[0] => hello
[1] => bye
)
[1] => Array
(
)
[2] => Array
(
)
)
Use array_map along with array_filter,
$array = array_filter(array_map('array_filter', $array));
Or just create a array_filter_recursive function
function array_filter_recursive($input)
{
foreach ($input as &$value)
{
if (is_array($value))
{
$value = array_filter_recursive($value);
}
}
return array_filter($input);
}
DEMO.
Note: that this will remove items comprising '0' (i.e. string with a numeral zero). Just pass 'strlen' as a second parameter to keep 0
Apply array_filter() on the main array and then once more on the inner elements:
$aryMain = array_filter($aryMain, function($item) {
return array_filter($item, 'strlen');
});
The inner array_filter() specifically uses strlen() to determine whether the element is empty; otherwise it would remove '0' as well.
To determine the emptiness of an array you could also use array_reduce():
array_filter($aryMain, function($item) {
return array_reduce($item, function(&$res, $item) {
return $res + strlen($item);
}, 0);
});
Whether that's more efficient is arguable, but it should save some memory :)

PHP in_array() not finding value [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
in_array() and multidimensional array
Got the following array returned from a database using this code:
$skus = array();
$result = mysql_query($sql);
if($result){
while($rows = mysql_fetch_array($result)){
$skus[]=$rows;
}
}
Results:
Array (
[0] => Array {
[0] => PUBELI
[group_sku] => PUBELI
)
[1] => Array (
[0] => PUBESSENTIALS
[group_sku] => PUBESSENTIALS
)
[2] => Array (
[0] => PUBMGRPROGROUPED
[group_sku] => PUBMGRPROGROUPED
)
[3] => Array (
[0] => PUB25GROUPED
[group_sku] => PUB25GROUPED
)
)
I'm looking for this value using in_array:
if (in_array('PUBESSENTIALS', $skus))
and it returns false. Am I doing this correctly?
Why would the array values not be enclosed in quotes if the values in the DB are strings?
Don't use PHP if you may do something with MySql!
Try this solution:
$sql = "SELECT * FROM table WHERE str = 'PUBESSENTIALS'"; // some query just add WHERE
$result = mysql_query($sql);
if($result) $Row = mysql_fetch_array($result)
Assuming $skus is the full array shown above, then 'PUBESSENTIALS' would not be in $skus, because $sku's contains child arrays.
However, in_array('PUBESSENTIALS', $skus[1]) would return true.
try looping through each $skus element, and then checking that child element for in_array(value, childArray)
You are only looking into the first array, and not any other array. You should look through each to test every sub-array. Something like this could do the job:
foreach($skus as $sku) {
if (in_array('PUBESSENTIALS', $sku)) {
return true;
}
}

Categories