PHP: How can i convert an index to an string? - php

how can i convert an index to an string ?
For example i would like to get the 'signin' index here:
array(1) {
["signin"]=>
array(2) {
["email_address"]=>
string(0) ""
["password"]=>
string(0) ""
}
}
Javi

You can use key():
reset($array); // resets the internal pointer to the first element,
// might not be necessary
$current_key = key($array);
// $current_key = 'singin';
Use array_keys() to get all keys of an array, e.g.:
$keys = array_keys('foo'=>1, 'bar'=>2);
// $keys[0] = 'foo'
// $keys[1] = 'bar'
To make sure that the key is a string you can use strval() (in case you also have numerical indecies).

......
$signin = $your_array["signin"];
To get the key, you can use the key
$key = key($your_array);
More info here: http://php.net/manual/en/function.key.php
The $signin itself is an array, you can check out:
print_r($signin);
So you can also get email address and password like this if you want:
$email = $your_array["signin"]["email_address"];
$password = $your_array["signin"]["password"];

Related

Loop through array with wildcard for element name

I am working a Rightmove BLM file and converting it into an array which is working fine.
However, the images are stored in sequential element nodes MEDIA_IMAGE_00, 01, 02 etc..
I am wondering if someone can advise me the best way to loop though those sequential elements using a wildcard or similar MEDIA_IMAGE_* for example.
Example of struture:
[MEDIA_IMAGE_00] => 003436_RX78401_IMG_00.jpg
[MEDIA_IMAGE_TEXT_00] =>
[MEDIA_IMAGE_01] => 003436_RX78401_IMG_01.jpg
[MEDIA_IMAGE_TEXT_01] =>
[MEDIA_IMAGE_02] => 003436_RX78401_IMG_02.jpg
[MEDIA_IMAGE_TEXT_02] =>
[MEDIA_IMAGE_03] => 003436_RX78401_IMG_03.jpg
Many Thanks!
The easiest solution might be:
foreach($array as $key=>$image)
{
if(str_contains($key, 'MEDIA_IMAGE_'))
{
//$image is your filename for the current image
}
}
But you can use RegEx instead.
In this case you just change the condition of the if to something like:
preg_match('/MEDIA_IMAGE_\d\d/', $key) === 1
You can use array_filter() in combination with an own filter-function.
Example
$inputArray['MEDIA_IMAGE_00'] = '003436_RX78401_IMG_00.jpg';
$inputArray['MEDIA_IMAGE_TEXT_00'] = '';
$inputArray['MEDIA_IMAGE_01'] = '003436_RX78401_IMG_01.jpg';
$inputArray['MEDIA_IMAGE_TEXT_01'] = '';
$inputArray['MEDIA_IMAGE_02'] = '003436_RX78401_IMG_02.jpg';
$inputArray['MEDIA_IMAGE_TEXT_02'] = '';
$inputArray['MEDIA_IMAGE_03'] = '003436_RX78401_IMG_03.jpg';
var_dump($inputArray);
/*
array(7) {
["MEDIA_IMAGE_00"]=>
string(25) "003436_RX78401_IMG_00.jpg"
["MEDIA_IMAGE_TEXT_00"]=>
string(0) ""
["MEDIA_IMAGE_01"]=>
string(25) "003436_RX78401_IMG_01.jpg"
["MEDIA_IMAGE_TEXT_01"]=>
string(0) ""
["MEDIA_IMAGE_02"]=>
string(25) "003436_RX78401_IMG_02.jpg"
["MEDIA_IMAGE_TEXT_02"]=>
string(0) ""
["MEDIA_IMAGE_03"]=>
string(25) "003436_RX78401_IMG_03.jpg"
}
*/
$inputArray = array_filter($inputArray, function($key) {
return preg_match('/MEDIA_IMAGE_\d\d/', $key) === 1;
}, ARRAY_FILTER_USE_KEY);
var_dump($inputArray);
/*
array(4) {
["MEDIA_IMAGE_00"]=>
string(25) "003436_RX78401_IMG_00.jpg"
["MEDIA_IMAGE_01"]=>
string(25) "003436_RX78401_IMG_01.jpg"
["MEDIA_IMAGE_02"]=>
string(25) "003436_RX78401_IMG_02.jpg"
["MEDIA_IMAGE_03"]=>
string(25) "003436_RX78401_IMG_03.jpg"
}
*/
If you just want to filter out empty values, you can even use filter_array() without any custom function. See the documentation for more information.
Documentation
array_filter() in php documentation.

Issue with passing values by reference into an array

I have an array named $initValues, which contains strings or numeric values and using a foreach loop I want to transfer the values to the $values array and the type of each value to $types.
Code:
$initValues = ["1-2", "2-1"];
$values = [];
$types = [];
foreach ($initValues as $value) {
$values[] = &$value; # by reference.
$types[] = gettype($value);
}
As you can see in the above code, I'm inserting the value by reference in $values, which is required by a function used later on, so that can't be changed. When I execute the above code and show the result using var_dump($values), I get the following:
array(2) { [0]=> &string(3) "2-1" [1]=> &string(3) "2-1" }
The problem with the above result is that essentially both elements of my $values array are the last element of $initValues and not both as in the desired result, which is:
array(2) { [0]=> &string(3) "1-2" [1]=> &string(3) "2-1" }
If I enter each value by value into the array the result is correct, but I'm facing a problem later on, so that's not an option. How can I modify my code, in order to produce the desired result?
Use an index in your foreach loop.
This should work:
$initValues = ["1-2", "2-1"];
$values = [];
$types = [];
foreach ($initValues as $ix=>$value) {
$values[] = &$initValues[$ix];
$types[] = gettype($value);
}
var_dump($values);

Can't assign 0 to an array if it was in an assocc in php.

Here's some php code. 0 is find in an associative array explicitly. If I try to put it in another one, it doesn't get assigned. The only way I know how to get around this is to explicitly check for it to be 0 using ===. Is this the only way?
<?php
$vars['one'] = '31234';
$vars['two'] = 'sldf';
$vars['three'] = 1 - 1;
$return_array = [];
foreach ($vars as $key => $value){
echo "---------------Just value<br>";
var_dump($value);
echo "<br>";
$value != '' ? ($return_array[$key] = $value) : null;
echo "---------------array of key<br>";
var_dump($return_array[$key]);
echo "<br>";
}
?>
I get this nice thing back.
---------------Just value
string(5) "31234"
---------------array of key
string(5) "31234"
---------------Just value
string(4) "sldf"
---------------array of key
string(4) "sldf"
---------------Just value
int(0)
---------------array of key
NULL
Any way better around this than if ($key === 0) { // stuff }?
You are using "loose comparison" when doing $value != ''. This evaluates to false for 0 also. See the table for loose comparison here.
If you used $value !== '' instead, it would insert the 0 to the array.

Get VALUES from url in PHP

I need to get ID´s from url:
http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID=1&ID=5&ID=24&ID=32
If i use $_GET['ID'] a still get only last ID value. I need to get all of them to array, or select.
Can anybody help me?
Use array syntax:
http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID[]=1&ID[]=5&ID[]=24&ID[]=32
var_dump($_GET['ID']);
array(4) {
[0]=>
int(1)
[1]=>
int(5)
[2]=>
int(24)
[3]=>
int(32)
}
}
echo $_GET['ID'][2]; // 24
The format in the URL is wrong. The second "ID" is overwriting the first "ID".. use an array:
http://www.example.org/?id[]=1&id[]=2&id[]=3
In PHP:
echo $_GET['id'][0]; // 1
echo $_GET['id'][1]; // 2
echo $_GET['id'][2]; // 3
To get this you need to make ID as array and pass it in the URL
http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID[]=1&ID[]=5&ID[]=24&ID[]=32
and this can be manipulated at the backend like this
$urls = $_GET['ID'];
foreach($urls as $url){
echo $url;
}
OR
An alternative would be to pass json encoded arrays
http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID=[1,2,24,32]
which can be used as
$myarr = json_decode($_GET['ID']); // array(1,2,24,32)
I recommend you to also see for this here.
http_build_query()
it's wrong but if you really want to do this
<?php
function getIds($string){
$string = preg_match_all("/[ID]+[=]+[0-9]/i", $string, $matches);
$ids = [];
foreach($matches[0] as $match)
{
$c = explode("=", $match);
$ids [] = $c[1];
}
return $ids;
}
// you can change this with $_SERVER['QUERY_STRING']
$url = "http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID=1&ID=5&ID=24&ID=32";
$ids = getIds($url);
var_dump($ids);

Changing values of multidimensional array php

Its my first time working with multidimensional arrays in php. I need to change the second number in each sub array.
What I want is to check if the Id in the array matches the Id from the database. When the two match I want to change the 2nd entry in the sub array by adding a number to it. If the Id from the query does not match anything in the list I want a new sub array to be pushed to the end of the array with the values of Id and points_description.
Also, if its helpful, my program right now does find the matches. The only thing is, it does not update the 2D array.
$array = array(array());
while ($row_description = mysqli_fetch_array($query_description)) {
$check = 1;
$is_match = 0;
foreach ($array as $i) {
foreach ($i as $value) {
if ($check == 1) {
if ($row_description['Id'] == $value) {
//$array[$i] += $points_description;
$is_match = 1;
}
}
$check++;
$check %= 2; //toggle between check and points
}
}
if ($is_match == 0) {
array_push($array, array($row_description['Id'], $points_description));
}
}
I feel like Im doing this so wrong. I just want to go through my 2D array and change every second value. The expected output should be a print out of all the Ids and their corresponding point value
I hope this is helpful enough.
Example: $row_description['Id'] = 2 and $array = array(array(2,1), array(5,1) , array(6,1))
output should be $array = array(array(2,4), array(5,1) , array(6,1))
if $row_description['Id'] = 3 and $array = array(array(2,1), array(5,1) , array(6,1))
output should be $array = array(array(2,4), array(5,1) , array(6,1),array(3,3))
By default PHP will copy an array when you use it in a foreach.
To prevent PHP from creating this copy you need to use to reference the value with &
Simple example :
<?php
$arrFoo = [1, 2, 3, 4, 5,];
$arrBar = [3, 6, 9,];
Default PHP behavior : Make a copy
foreach($arrFoo as $value_foo) {
foreach($arrBar as $value_bar) {
$value_foo *= $value_bar;
}
}
var_dump($arrFoo);
/* Output :
array(5) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
}
*/
ByReference : Don't create the copy :
foreach($arrFoo as &$value_foo) {
foreach($arrBar as $value_bar) {
$value_foo *= $value_bar;
}
}
var_dump($arrFoo);
/* Output :
array(5) {
[0]=>
int(162)
[1]=>
int(324)
[2]=>
int(486)
[3]=>
int(648)
[4]=>
&int(810)
}
*/

Categories