PHP - How to check if array contains a value by index? - php

Example:
$array = ['name', 'address'];
It contains $array[0] and $array[1] only.
If i try $array[2] i should receive an error.
So, i want to avoid these errors by checking it in a if statement. How can i check if an array contains a value in certain index?

You can use the isset function:
if(isset($array[2])) {

The second way to make it work is check how big is an array:
if(count($array) >= 3) { ... } // three or more elements: 0, 1, 2...

Related

Is there a php way to replicate a value multiple time in array, better than cycle?

I need to create an array with N variable instances of the same value.
The obvious solution is a for() cycle that appends the value to an array.
I wonder if it exists some more efficient solution, maybe a native function, for instance:
$var=1
DO_REPLICA($var,3);
the result should be:
[1,1,1]
Use array_fill
Fill an array with values
$var = 1;
$arr = array_fill(0, 3, $var);
The above code will create an array with $var from index 0 to the 3'th index
Try it online!

How to export each subarrays as an array in PHP

is it possible that, get arrays to $value with key:
Example:
$array = Array("one"=>Array("field1"=>"value1","field2"=>"value2"),
"two"=>Array("field3"=>"value3","field4"=>"value4"));
Export arrays to value:
$first = any_main_php_function_name(0,$array);
$second = any_main_php_function_name(1,$array);
Result:
$first = Array("field1"=>"value1","field2"=>"value2");
$second = Array("field3"=>"value3","field4"=>"value4");
Basically, I wanna extract multiple array. If there is no such function (any_main_php_function_name) in PHP so How can i extract above $array.
You don't need any funtion to do that. Simply get subarrays like this:
$first = $array['one'];
$second = $array['two'];
Unless you don't know the one,two keys, then you can use array_shift to get first item (one subarray). Remember that this functions also removes returned value from root array.
array_slice does what you want
$first = array_slice($array, 0, 1);
$second = array_slice($array, 1, 1);
print_r($first);
print_r($second);
May be you can array_shift to get the element from array, Like this:
$first_element=array_shift($array);
Make sure it only removes the first element from the array and
return the value of removed element.
And if you don't want to remove the element or get the sub-array in any sequence, then you can create a function like this,
function myFunction($index,$array) {
$keys = array_keys($array);
$sub_array=$arr[$keys[$index]];
}
In above function we just get the keys in a array and then use the known index to get the sub-array using keys array.
Please check this
foreach($array["one"] as $key=>$val){
echo "key=>".$key." Values=>".$val;
}
foreach($array["true"] as $key=>$val){
echo "key=>".$key." Values=>".$val;
}

PHP Single line array shuffle is not working

Very simple but I was wondering why this is not working.
I'm trying shuffle an array and output the results (in a single line structure)
this is my code :
echo shuffle(array("A","B","C"))[0];
Small tweak needed here ;)
Your basic logic is a little bit wrong. You're interested in only one value, I assume? To solve it with that logic in mind, you can do it like this:
echo array_rand(array_flip(['A', 'B', 'C']));
Try below code
$arr = array("A","B","C");
shuffle($arr);
echo $arr[0];
I know that this is not the best solution for you, but it works!
print_r( ( $b=array('A', 'B', 'C') ) && shuffle($b) ? next($b) : null );
How this works:
Assign the array to the variable $b
Shuffle the variable $b
If the shuffle() succeeded:
return the next element in the array
If the shuffle() failed:
return null
Some might think: "Why didn't he used the current() function?"
Well, it seems that the function shuffle simply changes the order of the keys, but the pointer is always pointing to the same element. This means that current() will always return 'A'.
Apparently, this behaviour changed on PHP 5.4 to set the pointer to the first element.
TRY THIS SIMPLE FUNCTION
$my_array = array("A","B","C","D","E");
shuffle($my_array);
print_r($my_array);
You will need to pass the array in a seperate variable. Also, shuffle() itself just returns a boolean value, so you need to return an array element instead of the output of the function.
$ar = array("A","B","C");
shuffle($ar);
echo $ar[0];

Undefined offset 1

I am facing a problem that undefined offset :1 in line 3. I can't understand that what type of error it is.
Can anyone tell me that why such error occurs in php
Undefined offset in line : 3
foreach ($lines as $line)
{
list($var,$value) = explode('=', $line); //line 3
$data[$var] = $value;
}
Your are getting PHP notice because you are trying to access an array index which is not set.
list($var,$value) = explode('=', $line);
The above line explodes the string $line with = and assign 0th value in $var and 1st value in $value. The issue arises when $line contains some string without =.
I know this an old question and the answer provided is sufficient.
Your are getting PHP notice because you are trying to access an array
index which is not set.
But I believe the best way to overcome the problem with undefined indexes when there are cases where you may have an empty array using the list()/explode() combo is to set default values using array_pad().
The reason being is when you use list() you know the number of variables you want from the array.
For example:
$delim = '=';
$aArray = array()
$intNumberOfListItems = 2;
list($value1, $value2) = array_pad(explode($delim, $aArray, $intNumberOfListItems ), $intNumberOfListItems , null);
Essentially you pass a third parameter to explode stating how many values you need for your list() variables (in the above example two). Then you use array_pad() to give a default value (in the above example null) when the array does not contain a value for the list variable.
This is caused because your $line doesn't contain "=" anywhere in the string so it contains only one element in array.list() is used to assign a list of variables in one operation. Your list contains 2 elements but as from data returned by implode, there is only one data. So it throws a notice.
A way to overcome that is to use array_pad() method.
list($var,$value) = array_pad(explode('=', $line),2,null);
by doing list($var, $value) php will expect an array of 2 elements, if the explode function doesn't find an equal symbol it will only return an array with 1 element causing the undefined offset error, offset 1 is the second element of an array so most likely one of your $line variables doesn't have an equal sign
This is due to the array. The array index is not showing due to this undefine offset error will come...
So please check the array with print_r function.
The list language construct is used to create individual variables from an array. If your array doesn't have enough elements for the number of variables you are expecting in the list call, you will get an error. In your case you have 2 variables so you need an array with 2 items - indexes 0 and 1.
http://php.net/manual/en/function.list.php
Solution:
$lines = array('one' => 'fruit=apple', 'two' => 'color=red', 'three' => 'language');
foreach ($lines as $line)
{
list($var,$value) = (strstr($line, '=') ? explode('=', $line) : array($line, ''));
$data[$var] = $value;
}
print_r($data);
Try this one..
For reference
http://in1.php.net/manual/en/function.list.php
http://in1.php.net/manual/en/function.explode.php

Get and remove first element of an array in PHP

Hi I am coding a system in which I need a function to get and remove the first element of the array. This array has numbers i.e.
0,1,2,3,4,5
how can I loop through this array and with each pass get the value and then remove that from the array so at the end of 5 rounds the array will be empty.
Thanks in advance
You can use array_shift for this:
while (($num = array_shift($arr)) !== NULL) {
// use $num
}
You might try using foreach/unset, instead of array_shift.
$array = array(0, 1, 2, 3, 4, 5);
foreach($array as $value)
{
// with each pass get the value
// use method to doSomethingWithValue($value);
echo $value;
// and then remove that from the array
unset($array[$value]);
}
//so at the end of 6 rounds the array will be empty
assert('empty($array) /* Array must be empty. */');
?>

Categories