Passing and returnging array to the functions - php

I have created two arrays. I wanna pass these two array to any function. I am beginner with function so tried with rough code to achieve my task. As I have some values in $cntctnum and $cntcttype named array.
$cntctnum = array();
$cntcttype = array();
$response = array();
function play_with_array($cntctnum, $cntcttype){
$contactnumber= $cntctnum[];
$cntcttype = $cntcttype[];
// some code to play with array.
return resultarray();
}
$response = play_with_array($cntctnum, $cntcttype);
Is this right way to pass function in array?
Is I need to declare $response as array before or when I return resultarray(), it will automatically consider it as array?

You don't need to define $response as array beforehand, but it might be a good idea to do so anyway depending on what the code afterwards expects.
In your function you don't return a function call resultarray() but a new array:
function play_with_array($cntctnum, $cntcttype) {
$contactNumber = $cntctnum; // You don't need the assignment! Note: No brackets here!
$resultArray = array();
// Do something here
return $resultArray;
}

You have:
$cntctnum = array();
$cntcttype = array();
$response = array();
function play_with_array($cntctnum, $cntcttype){
$contactnumber= $cntctnum[]; // don't need []
$cntcttype = $cntcttype[]; // don't need []
// some code to play with array.
return resultarray(); // this is a function?
}
$response = play_with_array($cntctnum, $cntcttype);
I would do something like this
$cntctnum = array();
$cntcttype = array();
function play_with_array($contactnumber, $cntcttype){
// some code to play with array.
$response = array($contactnumber,$cntcttype);
return $response;
}
$response = play_with_array($cntctnum, $cntcttype);
echo "<pre>".print_r($response,true)."</pre>";

Rahul, you pass array to a function just like you pass any other variable to a function. The reason to have a function is to have a block of code that can be re-used to perform the same set of calculations, etc.
It's hard to understand what you're trying to do inside your function. If this is something that's repeatable, meaning: compare array 1 vs array 2, get the bigger one, and return some sort of variation of that, then YES, create a function. If you have some code inside your function that is very specific to this page only and to these 2 arrays, you don't need the function. Just write the code inline.
Is I need to declare $response as array before or when I return resultarray(), it will automatically consider it as array?
No, you don't. If you resultarray variable inside a function is truly an array, you're good to go.

Related

Why does this way of adding values to an array in php work?

I use something like
$data = [];
foreach (){
$data[] = $api_content;
}
return $data;
the $data array does not get overwritten. Instead the values of $api_content get appended.
Is that right??? Why? I thought it gets overwritten....

Function returns "Array" instead of actual output

I have this code:
function returnArray() {
$intData = array("1", "3");
return $intData[array_rand($intData)];
}
I'm trying to make a function similar to the one above.
Instead of adding integers with commas I'm trying to implode the commas with the integers.
Sort of like a dynamic version of the above using json_decode, file_get_contents, a foreach loop, array, array_rand & return
This is my code:
function Something() {
foreach (json_decode(file_get_contents('removed'), true) as $jsonArr) {
$arrData = array(implode(",", $jsonArr));
$roundData = $arrData[array_rand($arrData)];
return $roundData;
}
}
I was just wondering if I'm doing it right and if the array is correct or not.
Also it doesn't return anything from the array.
When I try to implode, it throws an error
implode invalid argument
It seems you're trying to print a random room_id from the JSON response.
The problem lies here:
$intData = array(implode(",", $arrRoomsReverse['room_id']));
You can't initialize an array like that.
Just push the room_id element to the array, like so:
$intData[] = $arrRoomsReverse['room_id'];
Now, you can simply get a random room_id outside the loop:
$intRoom = $intData[array_rand($intData)];
The function would look like:
function returnArray()
{
$str = file_get_contents('...');
$jsonArr = json_decode($str, true);
foreach ($jsonArr as $arrRoomsReverse)
{
$intData[] = $arrRoomsReverse['room_id'];
}
$intRoom = $intData[array_rand($intData)];
return $intRoom;
}
And to call the function:
echo returnArray();

for loop and appending to an array in PHP

I have the following code:
$items = array();
foreach($following as $storeOwner)
{
array_push($items, $productRepository->mostRecentItem($storeOwner->getId(), 5));
}
I am trying to append the results of
$productRepository->mostRecentItem($storeOwner->getId(), 5)
to $items. How do I do so? Why doesn't the above code work?
Try this:
$items = array();
foreach($following as $storeOwner)
{
$items[] = $productRepository->mostRecentItem($storeOwner->getId(), 5);
}
Also, take a look to the result of the mostRecentItem Method... .
var_dump you different objects and return values to make sure that contain what you think they should contain. The code looks "correct" so it's probably the objects and values that are not.

PHP array merge: is not an array?

I'm tryin to merge an array that I have when it is being created through a function
I have a function, and it returns an array.
class myarray
{
public function getAr($id)
{
// mysql query
while($dd= $database->fetch(PDO::FETCH_ASSOC))
{
$data[] = $dd; //there's values in the array when its being populated through the function of the while loop
}
return $data;
}
public function get3($id)
{
// mysl query
while($dd= $database->fetch(PDO::FETCH_ASSOC))
{
$data[] = $dd; //there's values in the array when its being populated through the function of the while loop
}
return $data;
}
}
How come I tried to merge together the array:
$get = new myarray();
while($row = $fet->fetch(PDO::FETCH_ASSOC))
{
$arrayAr = $get->getAr($id);
$array3 = $get->get3($id);
$new_array = array_merge($arrayAr ,$array3); //this gives me the error
print_r($arrayAr); //displays array
}
print_r($arrayAr); //displays nothing, why is that?
It says that its not an array?
array_merge() [function.array-merge]: Argument #1 is not an array
But I can print_r($arrayAr); and its like an array inside the while loop, but it doesn't display anything outside of it?
when I tried this...
$new_array = array_merge((array)$arrayAr ,(array)$array3);
It doesn't display an error, but it isn't merged either.
Help?
Thanks
You $arrayAr is local variable and 2nd print_r() is used beyond of scope of his variable. If you need it available wider, "declare" it before foreach, with i.e. $arrayAr = array(); (or whatever value you want - it is not important in this case, yet array() makes code clear).

Make 1d Array from 1st member of each value in 2d Array | PHP

How can you do this? My code seen here doesn't work
for($i=0;i<count($cond);$i++){
$cond[$i] = $cond[$i][0];
}
It can be as simple as this:
$array = array_map('reset', $array);
There could be problems if the source array isn't numerically index. Try this instead:
$destinationArray = array();
for ($sourceArray as $key=>$value) {
$destinationArray[] = $value[0]; //you may want to use a different index than '0'
}
// Make sure you have your first array initialised here!
$array2 = array();
foreach ($array AS $item)
{
$array2[] = $item[0];
}
Assuming you want to have the same variable name afterwards, you can re-assign the new array back to the old one.
$array = $array2;
unset($array2); // Not needed, but helps with keeping memory down
Also, you might be able to, dependant on what is in the array, do something like.
$array = array_merge(array_values($array));
As previously stated, your code will not work properly in various situation.
Try to initialize your array with this values:
$cond = array(5=>array('4','3'),9=>array('3','4'));
A solution, to me better readable also is the following code:
//explain what to do to every single line of the 2d array
function reduceRowToFirstItem($x) { return $x[0]; }
// apply the trasnformation to the array
$a=array_map('reduceRowTofirstItem',$cond);
You can read the reference for array map for a thorough explanation.
You can opt also for a slight variation using array_walk (it operate on the array "in place"). Note that the function doesn't return a value and that his parameter is passed by reference.
function reduceToFirstItem(&$x) { $x=$x[0]; }
array_walk($cond, 'reduceToFirstItem');
That should work. Why does it not work? what error message do you get?
This is the code I would use:
$inArr;//This is the 2D array
$outArr = array();
for($i=0;$i<count($inArr);$i++){
$outArr[$i] = $inArr[$i][0];
}

Categories