php to create an array with value stored in variables - php

well, i have 2 variables
$variable1 = "123";
$variable2 = "321";
both variables are calculated by other methods and may vary due to change of circumstances, now i want to put these values in a single array for displaying, what i want is something like this
$array = ($variable1, $variable2)
and print like(in IDE)
array([0]=>123 [1]=>321)
both 123 and 321 are representations of variable values.
i tried compact() function but it gave me something weird, i tried make these two variables an array with only one element and merge them into one array but in fact i have many variables and it's infeasible to do this for every one of them.....please show me how i can do it and explain in detail the mechanism behind it, thank you very much.

There are several ways to do what you want.
You can use one of examples below :
// Define a new array with the values
$array1 = array($variable1, $variable2);
// Or
$array2 = [$variable1, $variable2];
// Debug
print_r($array1);
print_r($array2);
// Define an array and add the values next
$array3 = array();
$array3[] = $variable1;
$array3[] = $variable2;
// Debug
print_r($array3);
// Define an array and push the values next
// http://php.net/manual/en/function.array-push.php
$array4 = array();
array_push($array4, $variable1);
array_push($array4, $variable2);
// Debug
print_r($array4);

Just use the array function to get the values into one array.
$var1 = "123";
$var2 = "321";
$array = array($var1,$var2);
var_dump($array); returns:
array (size=2)
0 => string '123' (length=3)
1 => string '321' (length=3)
Or another example on how you could do it is:
$array = array();
$array[] = myFunction(); //myFunction returns a value and by using $array[] you can add the value to the array.
$array[] = myFunction2();
var_dump($array);

Here is your answer
$variable1 = "123";
$variable2 = "321";
$arr =array();
array_push($arr,$variable1);
array_push($arr,$variable2);
echo '<pre>';
print_r($arr);
Hope this will solve your problem.

As you want to put these item in array
First you have to initialize a variable
$newArray = []
After that you have to store the value in array which can be done by this
$newArray[] = $variable1;
// OR BY
array_push($newArray, $variable1);
They both are same it push the data to the end of the array
So your code will be like this
$newArray = []
$newArray[] = $variable1;
$newArray[] = $variable2;
If you want to do it in loop then do somthing like this
$newArray = []
foreach($values as $value){
$newArray[] = $value;
}
If there is a fix value then you can do like this
$newArray = [$variable1, $variable2];
//OR BY
$newArray = array($variable1, $variable2);
Both are same
And to print the value use
print_r($newArray);
Hope this will help

Related

How to get the exact value of the last array index in PHP?

Currently i have an array $newArr with some elements as shown in picture below. How do I know the last digit of the array index (highlighted in yellow)?
This is important because, if later I wanted to insert a new record into this $newArr array, I could just
$newArr[$the_variable_that_holds_the_last_digit + 1] = ['foo', 'bar'];
otherwise the whole array overwrite if
$newArr = ['foo', 'bar'];
I think you are looking for end pointer
$array = array(
'a' => 1,
'b' => 2,
'c' => 3,
);
end($array); // it will point to last key
$key = key($array); // get the last key using `key`
Assuming you have the numerically indexed array, the last index on your array is :
$last_index = count($newArr) -1;
if However your keys are not sequential, you can do this:
end($newArr);
$last_key = key($newArr);
I think you can try this
$array = end($newArr);
$last_index = key($array);//Its display last key of array
For more details, please follow this link.
If the only reason is to not overwrite the values you can use [] which means add new value.
$arr = [1,2,3,4];
var_dump($arr);
// incorrect way:
$arr = [1,2];
var_dump($arr);
//correct way
$arr = [1,2,3,4];
$arr[] = [1,2];
var_dump($arr);
See here for output: https://3v4l.org/ZTg28
The "correct way" will in the example above input a new array in the array.
If you want to add only the values you need to insert them one at the time.
$arr[] = 1;
$arr[] = 2;

PHP array_merge if not empty

Trying to merge 4 arrays, but some may be empty at certain times.
$array_1 = array('something1', something2);
$array_2 = array('something3', something4);
$array_3 = array();
$array_4 = array('something1', something2);
$list = array_merge($array_1,$array_2,$array_3,$array_4);
print_r($list);
But if one of the arrays are empty, there will be an error.
I've been googling forever, but I can't find a solid simple answer on how to check for empty arrays before merging.
Argument #2 is not an array
Or whichever array is empty is the argument number. How do I strip out empty arrays before merging?
There is NO error with an empty array. There is only an error if the arg is NOT an array.
You could check is_array() or:
$list = array_merge(
(array)$array_1,
(array)$array_2,
(array)$array_3,
(array)$array_4
);
Okay here you go, this should do the trick (if you make array of the initial arrays):
$arrs = array();
$arrs[] = array('something1', something2);
$arrs[] = array('something3', something4);
$arrs[] = array();
$arrs[] = array('something1', something2);
$list = array();
foreach($arrs as $arr) {
if(is_array($arr)) {
$list = array_merge($list, $arr);
}
}
print_r($list);
Array merge supports empty array()
Doc:
Example #3 Simple array_merge() example
http://us1.php.net/array_merge
<?php
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
?>
Result
Array
(
[0] => data
)
You are getting notice because something2, something4 should be quoted as string or $ as variable.
PHP Notice: Use of undefined constant something2 - assumed 'something2'

Variable array names

Fatal error: Cannot use string offset as an array
This appears when I try to find a array key by using variable array name:
class FOO {
protected $arr = array();
function bar(){
$aaaaaaaaaaaa = 'arr';
$this->$aaaaaaaaaaaa[$somekey]; // <-- error
...
}
}
How can I do this with variable array names?
#MarcinJuraszek's right, when you assign $arr the second time it's no longer an array.
Anyway, I believe this code does what you intend to
<?php
class foo
{
public function doStuff()
{
$name = 'arr';
$this->{$name} = array('Hello world!');
echo $this->{$name}[0];
}
}
$obj = new foo;
$obj->doStuff();
After that part of code:
$arr = 'arr';
$arr is no more an array. It's just a variable containing 'arr' string. So you can't access it as by key.
You should read information from PHP: Arrays - Manual.
$this->{$arr}[$somekey]
is what you want (provided that you actually assign array to $this->arr, not just $arr that you reassign later.
$arr is not an array. You first created one but then it's getting a string variable here: $arr = 'arr';.
This is correct:
$arr = array();
$arr[] = 'arr';
$somekey = 0;
$this->$arr[$somekey]
you are first defining $arr as an array, then you are OVER-writing its definition with a string. instead, maybe you wanted to add an element to the list:
$arr = array();
$somekey = 'mykey';
$arr[$somekey] = 'arrVal';
echo $arr[$somekey]
i think, i know what you want now:
a list of arrays...
$arr = array():
$arr['aaaaaaaaaa'] = array();
$arr['aaaaaaaaaa'][$somekey] = 'arrVal';
echo $arr['aaaaaaaaaaa'][$somekey]
and what's up with all the screaming?
After say
$arr = 'arr';
Variable $arr is no longer a variable, may be what you want to do is add that value to the array in which case try the following:
arr.push('arr');
Then it should work I think

Add tems to array with keys in PHP

How to add array items to an existing array with key => value ? actually i want to create an array of mysql rowset i.e.
$n =0;
while($row = mysql_fetch_array($rowset))
{
$array[$n] = array('name' => $row['name'], 'city' = $row['city']);
$n += 1;
}
Thanks.
Just try with:
$existingArray['newKey'] = 'new value';
Or use array_merge function:
$newArray = array_merge($existingArray, $additionalData);
http://php.net/manual/en/function.array-merge.php
That what you're looking for?
-edit-
Just to note, if conflicting results are found, the last most array entry will be used. If you array merge three arrays with id fields, only the final arrays id will be stored in the result.
You may want to look into this:
http://php.net/array_push
Should be simple enough.
For One:
$array['key'] = $value;
Merge:
$mergedArray = array_merge($array1, $array2);
(http://php.net/manual/en/function.array-merge.php)

"Classic" array in php

So, I'm starting a new project and working with php for the first time.
I get that the average definition and functioning of arrays in php is actually pretty much a namevalue combo.
Is there some syntax, API, or other terminology for just a simple list of items?
I.e. inserting something like ['example','example2','example3','example4'] that I can just call based off their index position of the array, without having to go in and modify the syntax to include 0 => 'example', etc...
This is a very shortlived array so im not worried about long term accessibility
php arrays are simple to use. You can insert into an array like:
$array=array('a','b','c'.....);
Or
$array[]="a";
$array[]="b";
$array[]="c";
or
array_push($array, "a");
array_push($array, "b");
array_push($array, "c");
array_push($array, "d");
and call them by their index values:
$array[0];
this will give you a
$yourArray = array('a','b','c');
or
$yourArray[] = 'a';
$yourArray[] = 'b';
$yourArray[] = 'c';
will get you an array with integer index values instead of an associative one..
You still can use array as "classic" arrays in php, just the way you think.
For example :
<?php
$array = array("First", "Second", "Third");
echo $array[1];
?>
You can then add different values <?php $array[] = "Forth"; ?> and it will be indexed in the order you specified it.
Notice that you can still use it as an associative array :
<?php
$array["newValue"] = "Fifth";
$array[1] = "ReplaceTheSecond";
$array[10] = "";
?>
Arrays in PHP can either be based on a key, like 0 or "key" => "value", or values can just be "appended" to the array by using $array[] = 'value'; .
So:
$mine = array();
$mine[] = 'test';
$mine[] = 'test2';
echo $mine[0];
Would produce 'test';
Haven't tested the code.

Categories