How to update data if array is empty? - php

I want to update empty array .So I check is empty and want to update the original variable.So I tried by & but it doesn't change empty array $array2 .I had tried many hours but not working!!!
<?php
$array1 = array('one','two','three');
$array2 = array();
$array3 = array ('four');
$array4 = array ('five','six');
check([&$array1,&$array2,&$array3,&$array4]);
function check($arr){
foreach ($arr as $k=>$value) {
if(empty($value)){
$arr[$k][] = "nothing";
return $arr[$k];
}
else{
return $arr[$k];
}
}
}
var_dump($array2);
//actual output : empty
//expect output : 0 => string 'nothing'
?>

Have a look following code.
$array1 = array('one','two','three');
$array2 = array();
$array3 = array ('four');
$array4 = array ('five','six');
$arr11=check([&$array1,&$array2,&$array3,&$array4]);
function check($arr){
foreach ($arr as $k=>$value) {
print_r($value);
if(empty($value)){
$arr[$k] = "nothing";
}
else{
$arr[$k];
}
}
return $arr;
}
print_r($arr11);
var_dump($array2);
//actual output : empty
//expect output : 0 => string 'nothing'
It will display following result.
Array
(
[0] => Array
(
[0] => one
[1] => two
[2] => three
)
[1] => nothing
[2] => Array
(
[0] => four
)
[3] => Array
(
[0] => five
[1] => six
)
)
string(7) "nothing"

This will work for you:
<?php
$array1 = array('one','two','three');
$array2 = array();
$array3 = array ('four');
$array4 = array ('five','six');
list($array1, $array2, $array3, $array4) = check([$array1,$array2,$array3,$array4]);
function check($arr){
foreach ($arr as $k => $value) {
if(empty($value)){
$arr[$k] = "nothing";
}
}
return $arr;
}
var_dump($array2);
//actual output : string(7) "nothing"
//expect output : string(7) "nothing"
?>
You've written your function very strangely, actually.
UPDATE. Output of other arrays instead of only one.
var_dump($array1, $array2, $array3, $array4);
array(3) {
[0]=>
string(3) "one"
[1]=>
string(3) "two"
[2]=>
string(5) "three"
}
string(7) "nothing"
array(1) {
[0]=>
string(4) "four"
}
array(2) {
[0]=>
string(4) "five"
[1]=>
string(3) "six"
}

Related

Create new Array under same key from multiple Array in PHP [duplicate]

This question already has answers here:
Transpose 2d array, join second level with commas, and join first level with pipes
(5 answers)
Closed 7 months ago.
I have the following array.
$a = array("Algebra", "Arithmetic");
$b = array("08/01/2020", "08/02/2019");
$c = array("08/01/2020", "08/02/2019");
print_r($a);
print_r($b);
print_r($b);
and the output is
Array(
[0] => Algebra
[1] => Arithmetic
)
Array(
[0] => 08/01/2020
[1] => 08/01/2019
)
Array(
[0] => 08/02/2020
[1] => 08/02/2019
)
And I want Array in the following structure.
Array(
[0] => Algebra,08/01/2020,08/02/2020
[1] => Arithmetic,08/01/2019,08/02/2019
)
I have tried $results = array_merge_recursive($a, $b, $c); but its not giving desire output.
Thanks for help in advance.
A simple foreach loop will suffice
$a = array("Algebra", "Arithmetic");
$b = array("08/01/2020", "08/02/2019");
$c = array("08/01/2020", "08/02/2019");
foreach( $a as $i=>$v ) {
$new[] = sprintf( '%s,%s,%s', $v, $b[$i], $c[$i] );
}
Firstly, when you find yourself using sequentially-named variables it almost always means that they should actually be an array:
$a = array("Algebra", "Arithmetic");
$b = array("08/01/2020", "08/02/2019");
$c = array("08/01/2020", "08/02/2019");
$better_array = [$a, $b, $c];
var_dump($better_array);
Output:
array(3) {
[0]=>
array(2) {
[0]=>
string(7) "Algebra"
[1]=>
string(10) "Arithmetic"
}
[1]=>
array(2) {
[0]=>
string(10) "08/01/2020"
[1]=>
string(10) "08/02/2019"
}
[2]=>
array(2) {
[0]=>
string(10) "08/01/2020"
[1]=>
string(10) "08/02/2019"
}
}
Once they're in an proper array you can use array_column()
$out = [];
for($i=0, $c=count($better_array[0]); $i < $c; ++$i) {
$out[] = array_column($better_array, $i);
}
var_dump($out);
Output:
array(2) {
[0]=>
array(3) {
[0]=>
string(7) "Algebra"
[1]=>
string(10) "08/01/2020"
[2]=>
string(10) "08/01/2020"
}
[1]=>
array(3) {
[0]=>
string(10) "Arithmetic"
[1]=>
string(10) "08/02/2019"
[2]=>
string(10) "08/02/2019"
}
}
And if that comma-delimited string is what you actually want, then use implode():
$out = [];
for($i=0, $c=count($better_array[0]); $i < $c; ++$i) {
$out[] = implode(',', array_column($better_array, $i));
}
var_dump($out);
Output:
array(2) {
[0]=>
string(29) "Algebra,08/01/2020,08/01/2020"
[1]=>
string(32) "Arithmetic,08/02/2019,08/02/2019"
}
Lastly, you should avoid print_r() as it tends to produce misleading output. Eg: https://3v4l.org/ThSLb
You don't get anything built-in for this purpose. You need to build a custom function for this. You can try this-
<?php
$a = array("Algebra", "Arithmetic");
$b = array("08/01/2020", "08/01/2019");
$c = array("08/02/2020", "08/02/2019");
function mergeAssoc()
{
// You can get variable number of arguments|array by this.
$args = func_get_args();
$master = array();
foreach ($args as $arg)
{
foreach ($arg as $i => $v)
{
$master[$i][] = $v;
}
}
return $master;
}
$res = mergeAssoc($a, $b, $c);
print_r($res);
Note: It will return a multidimensional array. Not an array of comma-separated values.
Output:
Array
(
[0] => Array
(
[0] => Algebra
[1] => 08/01/2020
[2] => 08/02/2020
)
[1] => Array
(
[0] => Arithmetic
[1] => 08/01/2019
[2] => 08/02/2019
)
)
and if we use foreach then our desire output will be there with array separated by comma.
foreach ($res as $key => $value) {
$result[] = implode(',', $value);
}
and output of print_r($result); is
Array
(
[0] => Algebra,08/01/2020,08/02/2020
[1] => Arithmetic,08/01/2019,08/02/2019
)

How to fill a empty value in KEY=> VALUE for array_combine in php

I wish to make Key and Value combining with 2 arrays, but both arrays are not equal.
$array1 = array("1","2","3","4","5");
$array2 = array("apple","banana","","dog","");
$key_value = array_combine($array1,$array2);
The output is:
array_combine(): Both parameters should have an equal number of elements
But I need to below output be like
print_r($key_value);
array(5) {
[1]=> string(5) "apple"
[2]=> string(6) "banana"
[3]=> string(8) "No Value"
[4]=> string(3) "dog"
[5]=> string(8) "No Value"
}
How can do this if null, insert "no value" text.
You can do it via foreach loop:
$res = [];
foreach($array1 as $ind=>$num){
$res[$num] = $array2[$ind] === "" ? "No Value" : $array2[$ind];
}
print_r($res);
Output:
Array
(
[1] => apple
[2] => banana
[3] => No Value
[4] => dog
[5] => No Value
)
Demo
use array_map() and array_combine()
<?php
$array1 = array("1","2","3","4","5");
$array2 = array("apple","banana","","dog","");
$array2 = array_map(function($v){
return (empty($v)) ? "No Value" : $v;
},$array2);
$key_value = array_combine($array1,$array2);
print_r($key_value);
https://3v4l.org/CY4ku

array_combine removed duplicate array

Array_combine remove duplicate array
<?php
$a1=array("red","red");
$a2=array("blue","yellow");
print_r(array_combine($a1,$a2));
?>
This code give output : Array ( [red] => yellow )
But I want output like this: Array ( [red] => blue [red] => yellow )
The Andreas answer is correct. you can do this:
$a1 = ['red'];
$a2 = ['blue', 'yellow'];
$a3 = [];
foreach($a1 as $item1) {
foreach($a2 as $item2) {
$a3[$item1][] = $item2;
}
}
print_r($a3);
The output:
array(1) {
["red"]=>
array(2) {
[0]=>
string(4) "blue"
[1]=>
string(6) "yellow"
}
}

Splitting string with braces into array

How do I split the OPTIONS column into array where the index of the array will be digit in the string. For example, using this
[OPTIONS] => {0: 'phy','chem','bio'},{1: 'webtech','algo'}
will result to
Array
(
[0] => [
[0] => 'phy',
[1] => 'chem',
[2] => 'bio'
],
[1] => [
[0] => 'webtech',
[1] => 'algo'
]
)
Index.php
<?php
try {
$pdo = new PDO('mysql:host=localhost;dbname=mydb','root','');
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Eror");
}
$stmt = $pdo->query("SELECT * FROM table");
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($data as $key) {
echo "<pre>";
print_r($key);
echo "</pre>";
}
?>
RESULT
stdClass Object
(
[ID] => 1
[FACULTY_NAME] => APPLIED SCIENCE
[DEPT] => SLT,COMPUTER SCIENCE,FOOD TECHNOLOGY,NUD,HMT,
[OPTIONS] => {0: 'phy','chem','bio'},{1: 'webtech','algo'}
)
A combination of different explodes and str_replace will get you the result.
I use both explode and multiexplode.
First I explode to the different subarrays, then I multiexplode the subarrays and the first value is the key and the rest is values, I split that with array_slice.
$str = "{0: 'phy','chem','bio'},{1: 'webtech','algo'}";
$arr = explode("},{", str_replace("'", "", $str));
foreach($arr as $a){
$temp = multiexplode([": ", ","], str_replace(["{", "}"], "", $a));
$res[$temp[0]] = array_slice($temp, 1);
}
var_dump($res);
function multiexplode ($delimiters,$string) {
$ready = str_replace($delimiters, $delimiters[0], $string);
$launch = explode($delimiters[0], $ready);
return $launch;
}
$res:
array(2) {
[0]=>
array(3) {
[0]=>
string(3) "phy"
[1]=>
string(4) "chem"
[2]=>
string(3) "bio"
}
[1]=>
array(2) {
[0]=>
string(7) "webtech"
[1]=>
string(4) "algo"
}
}
https://3v4l.org/YLLjI

How to Re-structure multi-dimensional array in PHP?

I have an array that looks like this:
array(3) {
[0]=>
array(2) {
[0]=>
string(10) "2012-11-14"
[1]=>
string(5) "3238"
}
[1]=>
array(2) {
[0]=>
string(10) "2012-11-13"
[1]=>
string(5) "3231"
}
[2]=>
array(2) {
[0]=>
string(10) "2012-11-13"
[1]=>
string(5) "3231"
}
I would like to write a foreach loop that would turn this array into:
array(2) {
[0]=>
array(1) {
"2012-11-14" => "3238"
}
[1]=>
array(1) {
"2012-11-13" => "3231"
}
So, basically, I would like to use the array element formatted as Y-M-D date as key to the second element in the array.
Given the following array...
$array = array(
0 => array(0 => "2012-11-14", 1 => "3238"),
1 => array(0 => "2012-11-13", 1 => "3231"),
2 => array(0 => "2012-11-13", 1 => "3231"),
);
putting it into a new array like this:
$new_array = array();
foreach ($array as $key => $item)
{
$new_array[$key][$item[0]] = $item[1];
}
print_r($new_array);
produces this output:
Array
(
[0] => Array
(
[2012-11-14] => 3238
)
[1] => Array
(
[2012-11-13] => 3231
)
[2] => Array
(
[2012-11-13] => 3231
)
)
My answer doesn't get rid of the duplicates, but the added dimension as specified in the original question means that duplicate dates as keys aren't an issue.
<?php
$data = array(
array("2012-11-14", "3238"),
array("2012-11-13", "3231"),
array("2012-11-13", "3231") // warning! when there are two record with same date, the second's count will be display
);
$result = array();
foreach ($data as $value) {
$result[$value[0]] = $value[1];
}
echo '<pre>';
print_r($result);
<?php
$newArray = array();
for($i=0;$i<count($arrayVariable);$i++)
{
$newArray[$arrayVariable[$i][0]] = $arrayVariable[$i][1];
}
echo '<pre>';print_r($newArray);echo '</pre>';
?>
Didn't test it but something like this should work in concept. Of course change arrayVariable to your variable.. but that aside.
You can use this code to get what you want:
$dates = array(
array("2012-11-01", "3238"),
array("2012-11-03", "4321")
);
print_r($dates);
$result = array();
foreach($dates as $value) {
$result[][$value[0]] = $value[1];
}
print_r($result);
The output will look like the requested form:
Array
(
[0] => Array
(
[2012-11-01] => 3238
)
[1] => Array
(
[2012-11-03] => 4321
)
)
Codepad demo: http://codepad.org/XAmUEdYh
However, I would personally prefer Aykut's solution. You would of course have a problem when you've got two records with the same date, but the overall array layout is a bit nicer ;).
Here is what I came up with:
<?php
$original = array(
array(
"2012-11-14",
"3238"
),
array(
"2012-11-13",
"3231"
),
array(
"2012-11-13",
"3231"
)
);
$newArray = array();
foreach($original as $subArray){
$newArray[] = array($subArray[0] => $subArray[1]);
}
var_dump($newArray);

Categories