Make array value variable (PHP) - php

Say I want to echo an array but I want to make the value in the array I echo variable, how would I do this?
Below is kind of an explanation of what I won't to do but it isn't the correct syntax.
$number = 0;
echo myArray[$number];

I'm not sure what you mean. What you have isn't working because you're missing a $ in myArray:
$myArray = array('hi','hiya','hello','gday');
$index = 2;
echo $myArray[$index]; // prints hello
$index = 0;
echo $myArray[$index]; // prints hi
Unlike other languages, all PHP variable types are preceded by a dollar sign.

Just to add more. Another type of array is associative array, where the element is determined using some identifier, usually string.
$arrayStates = array('NY' => 'New York', 'CA' => 'California');
To display the values, you can use:
echo $arrayStates['NY']; //prints New York
or, you can also use its numeric index
echo $arrayStates[1]; //prints California
To iterate all values of an array, use foreach or for.
foreach($arrayStates as $state) {
echo $state;
}
Remember, if foreach is used on non-array, it will produce warning. So you may want to do:
if(is_array($arrayStates)) {
foreach($arrayStates as $state) {
echo $state;
}
}
Hope that helps!

You are nearly there:
$number = 0;
$myArray = array('a', 'b')
echo $myArray[$number]; // outputs 'a'

$myArray = array("one","two","three","four");
$arrSize=sizeof($myArray);
for ($number = 0; $number < $arrSize; $number++) {
echo "$myArray[$number] ";
}
// Output: one two three four

$myArray = array('hi','hiya','hello','gday');
for($count=0;$count<count($myArray);$count++)
{
$SingleValue = $myArray[$count];
$AllTogether = $AllTogether.",".$SingleValue;
}

Related

Count how many numbers and letters in the variable using PHP

I'd like to count how many numbers and letters are in the variable using PHP. Below if my code:
$lot_num = strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
echo 'END UNIT: '.substr_count($lot_num, 'E').'<br />';
the code will count how many letter E are there in my lot_num variable but i would also like to count how many numbers are in the variable. Supposed, E1 and E18 should not be included when counting numbers.
I hope you can help me guys.
Try this: explode on , to get array that can be counted.
https://3v4l.org/r6OKl
$lot_num = strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
$ecount = substr_count($lot_num, 'E');
$totcount = count(explode(",", $lot_num));
echo 'END UNIT: '.$ecount;
Echo "\ntotal count: ". $totcount;
Echo "\nother count: ". Intval($totcount-$ecount);
No loops and no regex makes it a simple and quick solution.
You could always turn it into an array and use a loop:
$lot_num = explode(',',strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
$count = 0;
for ($i=0;$i<count($lot_num);$i++) {
if (is_int($lot_num[$i])) { //detects all numbers
$count++;
}
}
echo $count;
$lot_num = strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
$array = explode(',', $lot_num);
$data=array();
foreach($array as $k=>$val){
if(is_numeric($val )){
$data['number'][] = $val;
}else{
$data['string'][] = $val;
}
}
echo count($data['number']);
echo count($data['string']);
you can use is_numeric() and
if (!preg_match("/^[a-zA-Z]$/", $param)) {
// throw an Exception...
}
inside a loop
Id use preg_match
preg_match('/\b([0-9]+)\b/', $lot_num, $matches );
And matches would be like this.
$mathes[1][1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18]
So you would
$lot_num = strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
$total = 0;
if( preg_match('/\b([0-9]+)\b/', $lot_num, $matches )){
$total = count( $mathes[1] );
}
You can see how the Regx works here https://regex101.com/r/17psAQ/1
1,first u have to seperate the string and stored into array
2,then u can easily count the value of integers
<?php
$lot_num =explode(',',strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18'));//seperate string by ","
$arr_count=count($lot_num);
for($i=0;$i<$arr_count;$i++)
{
$get_num[]=$lot_num[$i];//saving seperated string value into array
}
$count=0;
for($j=0;$j<count($get_num);$j++)
{
if(is_numeric($get_num[$j]))//chect whether the value is integer or not
{
$count++;
}
}
echo $count;

Passing two variables into a 'foreach' loop

I need help regarding a foreach() loop. aCan I pass two variables into one foreach loop?
For example,
foreach($specs as $name, $material as $mat)
{
echo $name;
echo $mat;
}
Here, $specs and $material are nothing but an array in which I am storing some specification and material name and want to print them one by one. I am getting the following error after running:
Parse error: syntax error, unexpected ',', expecting ')' on foreach line.
In the Beginning, was the For Loop:
$n = sizeof($name);
for ($i=0; i < $n; $i++) {
echo $name[$i];
echo $mat[$i];
}
You can not have two arrays in a foreach loop like that, but you can use array_combine to combine an array and later just print it out:
$arraye = array_combine($name, $material);
foreach ($arraye as $k=> $a) {
echo $k. ' '. $a ;
}
Output:
first 112
second 332
But if any of the names don't have material then you must have an empty/null value in it, otherwise there is no way that you can sure which material belongs to which name. So I think you should have an array like:
$name = array('amy','john','morris','rahul');
$material = array('1w','4fr',null,'ff');
Now you can just
if (count($name) == count($material)) {
for ($i=0; $i < $count($name); $i++) {
echo $name[$i];
echo $material[$i];
}
Just FYI: If you want to have multiple arrays in foreach, you can use list:
foreach ($array as list($arr1, $arr2)) {...}
Though first you need to do this: $array = array($specs,$material)
<?php
$abc = array('first','second');
$add = array('112','332');
$array = array($abc,$add);
foreach ($array as list($arr1, $arr2)) {
echo $arr1;
echo $arr2;
}
The output will be:
first
second
112
332
And still I don't think it will serve your exact purpose, because it goes through the first array and then the second array.
You can use the MultipleIterator of SPL. It's a bit verbose for this simple use case, but works well with all edge cases:
$iterator = new MultipleIterator();
$iterator->attachIterator(new ArrayIterator($specs));
$iterator->attachIterator(new ArrayIterator($material));
foreach ($iterator as $current) {
$name = $current[0];
$mat = $current[1];
}
The default settings of the iterator are that it stops as soon as one of the arrays has no more elements and that you can access the current elements with a numeric key, in the order that the iterators have been attached ($current[0] and $current[1]).
Examples for the different settings can be found in the constructor documentation.
This is one of the ways to do this:
foreach ($specs as $k => $name) {
assert(isset($material[$k]));
$mat = $material[$k];
}
If you have ['foo', 'bar'] and [2 => 'mat1', 3 => 'mat2'] then this approach won't work but you can use array_values to discard keys first.
Another apprach would be (which is very close to what you wanted, in fact):
while ((list($name) = each($specs)) && (list($mat) = each($material))) {
}
This will terminate when one of them ends and will work if they are not indexed the same. However, if they are supposed to be indexed the same then perhaps the solution above is better. Hard to say in general.
Do it using a for loop...
Check it below:
<?php
$specs = array('a', 'b', 'c', 'd');
$material = array('x', 'y', 'z');
$count = count($specs) > count($material) ? count($specs) : count($material);
for ($i=0;$i<$count;$i++ )
{
if (isset($specs[$i]))
echo $specs[$i];
if (isset($material[$i]))
echo $material[$i];
}
?>
OUTPUT
axbyczd
Simply use a for loop. And inside that loop, extract values of your array:
For (I=0 to 100) {
Echo array1[i];
Echo array2[i]
}

Iterate on PHP variable (list/array) then output the index based on its value

Using the following example in PHP:
$priv['PAGE_A'] = 11;
$priv['PAGE_B'] = 22;
$priv['PAGE_C'] = 33;
$priv['PAGE_D'] = 44;
1) I would like to iterate on the 4 values in $priv. Would 'foreach' be the correct way to do it?
2) If the value is higher than a given number, I would like to echo the index of this value. Not sure how to do it. The comparaison must be INT (not string).
Ex. using "30" it would output:
PAGE_C
PAGE_D
Is it possible? Or maybe I am not using the correct container for what I'm trying to do ?
PS. How would you call the type of "$priv" in this example ? An array ? An indexed variable ? A dictionary ? A list ?
Thank you.
basically:
<?php
function foo($var){
$priv['PAGE_A'] = 11;
$priv['PAGE_B'] = 22;
$priv['PAGE_C'] = 33;
$priv['PAGE_D'] = 44;
$out='';
foreach ($priv as $k=>$v){
if ($v >$var){
$out .= $k.'<br>';
}
}
return $out;
}
echo foo('30');
demo: http://codepad.viper-7.com/GNX7Gf
Just create an array with the letters to iterate over.
$letters = array('A','B','C','D');
for($i=0;$i<count($letters);$i++) {
if($priv['PAGE_' . $letters[$i]] > /*value*/) {
echo $priv['PAGE_' . $letters[$i]];
}
}
$priv is an array.
Also, it's not too clear to me what you are exactly trying to do. Are you trying to echo the value of the array element if it's greater than a constant value?
We could do it using PHP builtin array functions. Its good to use builtin functions if possible in case of performance.
array_walk will do the trick for you. In this case $priv is an associative PHP array. Following is the one line script that will do what you want to achieve:
$input = 30;
$priv['PAGE_A'] = 11;
$priv['PAGE_B'] = 22;
$priv['PAGE_C'] = 33;
$priv['PAGE_D'] = 44;
array_walk($priv, function($value, $key, $input){ if($value > $input) echo $key . '<br>';}, $input);

Effective way to get array index and value names

I have a 0 indexed array that I can't do much about, but inside this array there are values that I need to echo. example array is:
$x = array(0 => array('store'=> 107));
I would like to have 2 variables that both echo texts store and 107
I could do this, using
$var1 = array_keys($x[0]);
$var2 = array_values($x[0]);
echo $var1[0]; // store
echo $var2[0]; // 107
I would like to know if there is a more effective way of getting those values, or remving that first 0 index. as array_filter($x) or unset($x) obviously don't work as in other cases.
As an alternative, you could also use combinations of key() and reset() if you're curious.
$x = array(0 => array('store'=> 107));
$y = reset($x); // point to first element
$key = key($y); // get the current key, store
$val = reset($y); // get the value
echo $key; // store
echo $val; // 107
this should work for you.
$x = array(0 => array('store'=> 107));
foreach($x as $y){
foreach ($y as $key => $value){
echo $key;
echo $value;
}
}

Better way to print out data from only the first index in an array full of objects?

Option 1:
$foo = array($obj1, $obj2, $obj3);
for ($i = 0; $i < 1; $i++) {
echo $foo[$i]->attribute;
echo $foo[$i]->attribute2;
}
//shows obj1's attribute and attribute2
Option 2:
$foo = array($obj1, $obj2, $obj3);
$first_foo = array_shift($foo); /* now we only have the first index in the new array */
foreach ($first_foo as $object) {
echo $object->attribute;
echo $object->attribute2;
}
//shows obj1's attribute and attribute2
Option 3:
$foo = array($obj1, $obj2, $obj3);
$first_foo = $foo[0] /* now we just have an object, obj1 */
echo $first_foo->attribute;
echo $first_foo->attribute2;
//shows obj1's attribute and attribute2
I used Option 3, but all of these feel kinda lacking... how would you do this? Is the loop in options 1 and 2 worth it if you feel like easily pulling the first two instead of one later on? I.e. pulling the latest news article vs. pulling the latest two etc.
Why so complicated?
Loops, array_shift(), ... it's all not neccessary.
You gave the solution yourself:
$foo[0]->attribute
Another one would be
reset($foo)->attribute
On your edit:
If you want to write the code so it is flexible later, do
$need = 1; // the variable number of elements you need
for($i = 0; $i < $need; $i++)
echo $foo[$i]->attribute;
The two iterations aren't needed in this case. I would just take your option #3 with a little less code.
$foo = array($obj1, $obj2, $obj3);
echo $foo[0]->attribute;
echo $foo[0]->attribute2;
assuming:
$b = [0,1];
$c = [2,3];
let:
$a = [$b,$c];
$first_elem = array_shift($a);
print_r($first_elem);
This is to get more than 1 from array_shift which returns null after array is empty
$foo = array($obj1, $obj2, $obj3);
while($obj = array_shift($foo))
echo $obj->attribute;
your option 2 can be changed to
$foo = array($obj1, $obj2, $obj3);
foreach ($foo as $object) {
echo $object->attribute;
echo $object->attribute2;
}
why don't use use it that way?

Categories